﻿using System;
using System.Data;
using System.Data.Common;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Reflection;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Collections.Specialized;

namespace PTA.Db
{
    #region 数据库访问接口
    /// <summary>
    /// 数据库访问接口
    /// </summary>
    public interface IDataAccess
    {
        /// <summary>
        /// 获取或设置连接字符串
        /// </summary>
        string ConnectionString
        {
            get;
        }

        #region 通用方法
        /// <summary>
        /// 创建一个数据库连接
        /// </summary>
        /// <returns>返回创建的数据库连接</returns>
        IDbConnection CreateConnection();

        /// <summary>
        /// 返回数据库类型
        /// </summary>
        DbProvider Provider
        {
            get;
        }

        string ParameterPrefix
        {
            get;
        }
        #endregion

        #region 返回影响的行数

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回受影响的行数</returns>
        NonQueryResult ExecuteNonQuery(string commandText);

        /// <summary>
        /// 执行数据库存储过程,返回受影响的行数
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回受影响的行数</returns>
        NonQueryResult ExecuteNonQuery(string commandText, params object[] ps);

        #endregion 执行数据库命令,返回受影响的行数

        #region 执行数据库命令，返回一个或多个对象
        /// <summary>
        /// 读取一个对象，如果没有查到，返回null
        /// </summary>
        /// <typeparam name="O">对象类型</typeparam>
        /// <param name="commandText">SQL脚本</param>
        /// <returns></returns>
        O ExecuteEntity<O>(string commandText) where O : BaseEntity, new();

        /// <summary>
        /// 读取一个对象，如果没有查到，返回null
        /// </summary>
        /// <typeparam name="O">对象类型</typeparam>
        /// <param name="commandText">SQL脚本</param>
        /// <param name="args">构造函数参数</param>
        /// <returns></returns>
        O ExecuteEntity<O>(string commandText, object[] args) where O : BaseEntity;

        /// <summary>
        /// 读取对象数组
        /// </summary>
        /// <typeparam name="O"></typeparam>
        /// <param name="commandText"></param>
        /// <param name="ps"></param>
        /// <returns></returns>
        List<O> ExecuteEntityArray<O>(string commandText) where O : BaseEntity, new();


        /// <summary>
        /// 读取对象数组
        /// </summary>
        /// <typeparam name="O"></typeparam>
        /// <param name="commandText"></param>
        /// <param name="args">构造函数参数</param>
        /// <returns></returns>
        List<O> ExecuteEntityArray<O>(string commandText, object[] args) where O : BaseEntity;
        #endregion

        #region 执行数据库命令,返回结果的第一行第一列

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回结果的第一行第一列</returns>
        ScalerResult ExecuteScalar(string commandText);

        /// <summary>
        /// 执行数据库存储过程,返回结果的第一行第一列
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回结果的第一行第一列</returns>
        ScalerResult ExecuteScalar(string commandText, params object[] ps);

        #endregion 执行数据库命令,返回结果的第一行第一列

        #region 执行数据库命令,返回一个DataReader

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据读取器</returns>
        DataReader ExecuteReader(string commandText);

        /// <summary>
        /// 执行数据库存储过程,返回一个数据读取器
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回一个数据读取器</returns>
        DataReader ExecuteReader(string commandText, params object[] ps);

        #endregion  执行数据库命令,返回一个DataReader

        #region 执行数据库命令,返回一个数据表

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据表</returns>
        DataTableResult ExecuteDataTable(string commandText);

        /// <summary>
        /// 执行数据库存储过程,返回一个数据表
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回一个数据表</returns>
        DataTableResult ExecuteDataTable(string commandText, params object[] ps);

        #endregion 执行数据库命令,返回一个数据表

        #region 执行数据库命令,返回一个数据集

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据集</returns>
        DataSetResult ExecuteDataSet(string commandText);

        /// <summary>
        /// 执行数据库存储过程,返回一个数据集
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回一个数据集</returns>
        DataSetResult ExecuteDataSet(string commandText, params object[] ps);
        #endregion 执行数据库命令,返回一个数据集

        #region 执行事务
        /// <summary>
        /// 执行一系列的事务(返回最后一条语句影响的行数)
        /// </summary>
        /// <param name="commands">数据库命令</param>
        int ExecuteTransaction(IList<string> commands);
        #endregion

        #region 格式化数据

        /// <summary>
        /// 把一个对象化成为一个可用的SQL数据
        /// </summary>
        /// <param name="value">对象</param>
        /// <returns>格式化后的字符串</returns>
        string ToSqlValue(object value);

        /// <summary>
        /// 把一个整型列表创建一个IN表达式
        /// </summary>
        /// <param name="colume">列名</param>
        /// <param name="value">IN表达式的值列表</param>
        /// <returns>创建后的IN表达式</returns>
        string BuildInSql<DT>(string colume, IEnumerable<DT> values, Func<DT, string> convert = null);

        /// <summary>
        /// 把一个整型列表创建一个IN表达式
        /// </summary>
        /// <param name="colume">列名</param>
        /// <param name="length">IN表达式的最大长度(如Oracle最大长度为8000)</param>
        /// <param name="value">IN表达式的值列表</param>
        /// <returns>创建后的IN表达式</returns>
        string BuildInSql<DT>(string colume, int length, IEnumerable<DT> values, Func<DT, string> convert = null);
        #endregion

        #region 执行事务,最后返回一个ScalerResult对象

        /// <summary>
        /// 执行一系列的事务,最后一个SQL命令返回Scaler对象
        /// </summary>
        /// <param name="commands">数据库命令</param>
        ScalerResult ExecuteScalerTransaction(IList<string> commands);

        #endregion

        #region 实体插入更新删除
        /// <summary>
        /// 插入一个实体
        /// </summary>
        /// <param name="m"></param>
        void Insert(BaseEntity m);

        /// <summary>
        /// 更新一个实体
        /// </summary>
        /// <param name="m">返回一个值,指示影响的行数</param>
        int Update(BaseEntity m);

        /// <summary>
        /// 获取指定实体类型关联的表
        /// </summary>
        /// <typeparam name="E"></typeparam>
        /// <returns></returns>
        string GetTable<E>() where E : BaseEntity;
        #endregion
    }
    #endregion

    #region 数据库访问类
    /// <summary>
    /// 数据库访问类
    /// </summary>
    /// <typeparam name="C">数据库连接类型</typeparam>
    /// <typeparam name="A">数据库适配器类型</typeparam>
    /// <typeparam name="T">数据库事务类型</typeparam>
    /// <typeparam name="P">数据命令参数类型</typeparam>
    public abstract class DataAccess<C, A, T, P, CMD, PS> : IDataAccess
        where C : class, IDbConnection, new()
        where A : class, IDbDataAdapter
        where T : class, IDbTransaction
        where P : class, IDbDataParameter, new()
        where CMD : DataCommand<P>, new()
        where PS : IPageSearch<P>, new()
    {
        internal static LogAdapter Log = LogAdapter.GetLogger("Db");

        /// <summary>
        /// 创建线程安全的保存数据库命令参数的表.
        /// </summary>
        private Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        private string connectionString;
        /// <summary>
        /// 获取或设置连接字符串
        /// </summary>
        public string ConnectionString
        {
            get
            {
                return this.connectionString ?? string.Empty;
            }
        }

        static CommandType GuessCommandType(string commandText)
        {
            return commandText.Trim().Contains(" ") ? CommandType.Text : CommandType.StoredProcedure;
        }

        #region 通用方法
        private Version version = new Version();

        private DbProvider provider = DbProvider.SqlServer;
        /// <summary>
        /// 返回数据库类型
        /// </summary>
        public DbProvider Provider
        {
            get
            {
                return this.provider;
            }
        }

        /// <summary>
        /// 是否写出调试信息
        /// </summary>
        protected bool WriteDebug
        {
            set
            {
                if (value)
                {
                    Log.Level = ResultBase.Log.Level = LogLevel.Debug;
                }
            }
        }
        public abstract string ParameterPrefix
        {
            get;
        }

        /// <summary>
        /// 默认的构造函数
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        internal DataAccess(string connectionString)
        {
            this.connectionString = connectionString;
            this.provider = GetDbProvider(typeof(C));

            #region 获取 Version
            switch (this.provider)
            {
                case DbProvider.SqlServer:
                    {
                        //this.parameterPrefix = "@";
                        #region SqlServer
                        try
                        {
                            version = new Version(this.ExecuteScalar("SELECT  SERVERPROPERTY('PRODUCTVERSION')").StringValue);
                        }
                        catch
                        {
                            version = new Version(8, 0); //默认为2000
                        }
                        break;
                        #endregion
                    }
                case DbProvider.FireBird:
                    {
                        #region FireBird
                        try
                        {
                            version = new Version(this.ExecuteScalar("SELECT RDB$GET_CONTEXT('SYSTEM', 'ENGINE_VERSION') FROM RDB$DATABASE").StringValue);
                        }
                        catch
                        {
                            version = new Version(1, 0); //默认为1.0
                        }
                        break;
                        #endregion
                    }
                case DbProvider.MySql:
                    {

                        #region MySql
                        version = new Version(5, 0); //默认为1.0
                        //try
                        //{
                        //    MatchCollection mc = Lvl.Regular.Matches(@"\d{1,2}(\.(\d{1,10})){0,3}", this.ExecuteScalar("SELECT VERSION()").StringValue, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if (mc.Count > 0)
                        //    {
                        //        version = new Version(mc[0].Value);
                        //    }
                        //    else
                        //    {
                        //        version = new Version(5, 0);
                        //    }
                        //}
                        //catch
                        //{
                        //    version = new Version(5, 0); //默认为1.0
                        //}
                        break;
                        #endregion
                    }
                case DbProvider.Oracle:
                    {
                        #region Oracle
                        version = new Version(9, 2);
                        //try
                        //{
                        //    MatchCollection mc = Lvl.Regular.Matches(@"\d{1,2}(\.(\d{1,10})){0,3}", this.ExecuteScalar("SELECT * FROM PRODUCT_COMPONENT_VERSION").StringValue, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        //    if (mc.Count > 0)
                        //    {
                        //        version = new Version(mc[0].Value);
                        //    }
                        //    else
                        //    {
                        //        version = new Version(10, 2);
                        //    }
                        //}
                        //catch
                        //{
                        //    version = new Version(10, 2);
                        //}
                        break;
                        #endregion
                    }
                case DbProvider.Sqlite:
                    {
                        //this.parameterPrefix = "@";
                        break;
                    }
                case DbProvider.SqlCe:
                    {
                        //this.parameterPrefix = "@";
                        break;
                    }
                case DbProvider.VistaDB:
                    {
                        //this.parameterPrefix = "@";
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
            #endregion
        }

        IDbConnection IDataAccess.CreateConnection()
        {
            return this.CreateConnection();
        }

        /// <summary>
        /// 创建一个连接对象
        /// </summary>
        /// <returns></returns>
        public virtual C CreateConnection()
        {
            C conn = new C();
            conn.ConnectionString = this.connectionString;
            return conn;
        }

        private void CheckHasException(DataReader dr)
        {
        }
        /// <summary>
        /// 压缩数据库
        /// </summary>
        public void Compress()
        {
            string sql = string.Empty;
            switch (this.Provider)
            {
                case DbProvider.Sqlite:
                    {
                        sql = "VACUUM";
                        break;
                    }
            }
            if (!string.IsNullOrEmpty(sql))
            {
                ExecuteNonQuery(sql);
            }
        }

        #endregion

        #region 参数管理

        /// <summary>
        /// 获取存储过程的参数
        /// </summary>
        /// <param name="procName">存储过程名称</param>
        /// <returns>存储过程的参数数组</returns>
        protected abstract P[] GetProcParameters(string procName);

        /// <summary>
        /// 缓存数据库命令参数
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="ps">参数列表,如果参数不继承ICloneable,则不缓存</param>
        public P[] SaveParameters(string key, params P[] ps)
        {
            if (ps.Length > 0 && ps[0] is ICloneable)
            {
                parmCache[key] = ps;
            }
            return ps;
        }

        /// <summary>
        /// 从缓存中获取数据库命令参数
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>数据库命令参数</returns>
        public P[] GrabParameters(string key)
        {
            if (parmCache.ContainsKey(key))
            {
                P[] cachedParms = (P[])parmCache[key];
                P[] clonedParms = new P[cachedParms.Length];
                if (cachedParms[0] is ICloneable)
                {
                    for (int i = 0, j = cachedParms.Length; i < j; i++)
                    {
                        clonedParms[i] = (P)((ICloneable)cachedParms[i]).Clone();
                    }
                }
                else
                {
                    for (int i = 0, j = cachedParms.Length; i < j; i++)
                    {
                        clonedParms[i] = new P();
                        clonedParms[i].ParameterName = cachedParms[i].ParameterName;
                        clonedParms[i].DbType = cachedParms[i].DbType;
                        clonedParms[i].Direction = cachedParms[i].Direction;
                        clonedParms[i].Size = cachedParms[i].Size;
                        clonedParms[i].Precision = cachedParms[i].Precision;
                        clonedParms[i].Scale = cachedParms[i].Scale;
                    }
                }
                return clonedParms;
            }
            return null;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <returns>数据库命令参数</returns>
        public P MakeIn(string name)
        {
            P p = new P();
            p.ParameterName = name;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="value">参数值</param>
        /// <returns>数据库命令参数</returns>
        public P MakeIn(string name, object value)
        {
            P p = new P();
            p.ParameterName = name;
            p.Value = value;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="type">参数类型</param>
        /// <returns>数据库命令参数</returns>
        public P MakeIn(string name, DbType type)
        {
            P p = new P();
            p.ParameterName = name;
            p.DbType = type;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="type">参数类型</param>
        /// <param name="size">参数长度</param>
        /// <returns>数据库命令参数</returns>
        public P MakeIn(string name, DbType type, int size)
        {
            P p = new P();
            p.ParameterName = name;
            p.Size = size;
            p.DbType = type;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="value">参数值</param>
        /// <param name="type">参数类型</param>
        /// <param name="size">参数长度</param>
        /// <returns>数据库命令参数</returns>
        public P MakeIn(string name, DbType type, int size, object value)
        {
            P p = new P();
            p.ParameterName = name;
            p.Value = value;
            p.DbType = type;
            p.Size = size;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="type">参数类型</param>
        /// <returns>数据库命令参数</returns>
        public P MakeOut(string name, DbType type)
        {
            P p = new P();
            p.ParameterName = name;
            p.DbType = type;
            p.Direction = ParameterDirection.Output;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="type">参数类型</param>
        /// <param name="size">参数长度</param>
        /// <returns>数据库命令参数</returns>
        public P MakeOut(string name, DbType type, int size)
        {
            P p = new P();
            p.ParameterName = name;
            p.DbType = type;
            p.Size = size;
            p.Direction = ParameterDirection.Output;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="value">参数值</param>
        /// <param name="type">参数类型</param>
        /// <param name="direction">参数方向</param>
        /// <param name="size">参数长度</param>
        /// <returns>数据库命令参数</returns>
        public P MakeParam(string name, object value, DbType type, ParameterDirection direction, int size)
        {
            P p = new P();
            p.ParameterName = name;
            if (value != null)
            {
                p.Value = value;
            }
            if (size > 0)
            {
                p.Size = size;
            }
            p.DbType = type;
            p.Direction = direction;
            return p;
        }
        #endregion

        #region 返回影响的行数

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(string commandText)
        {
            return ExecuteNonQuery(commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库存储过程,返回受影响的行数
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(string commandText, params object[] ps)
        {
            P[] pvs = GrabParameters(commandText);
            if (pvs == null)
            {
                pvs = GetProcParameters(commandText);
            }
            for (int i = 0; i < pvs.Length && i < ps.Length; i++)
            {
                pvs[i].Value = ps[i];
            }
            return ExecuteNonQuery(commandText, CommandType.StoredProcedure, pvs);
        }

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(C connection, string commandText)
        {
            return ExecuteNonQuery(connection, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(T transaction, string commandText)
        {
            return ExecuteNonQuery(transaction, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(string commandText, params P[] commandParameters)
        {
            return ExecuteNonQuery(commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(C connection, string commandText, params P[] commandParameters)
        {
            return ExecuteNonQuery(connection, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(T transaction, string commandText, params P[] commandParameters)
        {
            return ExecuteNonQuery(transaction, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (C cn = this.CreateConnection())
            {
                return ExecuteNonQuery(cn, commandText, commandType, commandParameters);
            }
        }

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(C connection, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = connection.CreateCommand())
            {
                using (var dr = ExecuteReader(connection, commandText, commandType, commandParameters))
                {
                    dr.Close();
                    return new NonQueryResult(dr.RecordsAffected, cmd, this);
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,返回受影响的行数
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(T transaction, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                using (var dr = ExecuteReader(transaction, commandText, commandType, commandParameters))
                {
                    dr.Close();
                    return new NonQueryResult(dr.RecordsAffected, cmd, this);
                }
            }
        }

        /// <summary>
        /// 执行数据库命令
        /// </summary>
        /// <param name="command">数据库命令对象</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(DataCommand<P> command)
        {
            return ExecuteNonQuery(command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="command">数据库命令对象</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(C connection, DataCommand<P> command)
        {
            return ExecuteNonQuery(connection, command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="command">数据库命令对象</param>
        /// <returns>返回受影响的行数</returns>
        public NonQueryResult ExecuteNonQuery(T transaction, DataCommand<P> command)
        {
            return ExecuteNonQuery(transaction, command.CommandText, command.CommandType, command.Parameters);
        }
        #endregion 执行数据库命令,返回受影响的行数

        #region 分页查询
        /// <summary>
        /// 执行SQL语句,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(PS search)
        {
            search.TotalCount = ExecuteScalar(CreateCountSql(search), search.Parameters).IntValue;
            int skip;
            string sql = CreatePageSql(search, Provider, version, out skip);
            DataReader dr = ExecuteReader(sql, search.Parameters);
            dr.Skip(skip);
            return dr;
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(C connection, PS search)
        {
            search.TotalCount = ExecuteScalar(connection, CreateCountSql(search), search.Parameters).IntValue;
            int skip;
            string sql = CreatePageSql(search, Provider, version, out skip);
            DataReader dr = ExecuteReader(connection, sql, search.Parameters);
            dr.Skip(skip);
            return dr;
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据读取器
        /// </summary>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(T transaction, PS search)
        {
            search.TotalCount = ExecuteScalar(transaction, CreateCountSql(search), search.Parameters).IntValue;
            int skip;
            string sql = CreatePageSql(search, Provider, version, out skip);
            DataReader dr = ExecuteReader(transaction, sql, search.Parameters);
            dr.Skip(skip);
            return dr;
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据读取器</returns>
        public List<O> ExecuteEntityArray<O>(PS search) where O : BaseEntity, new()
        {
            search.TotalCount = ExecuteScalar(CreateCountSql(search), search.Parameters).IntValue;
            int skip;
            string sql = CreatePageSql(search, Provider, version, out skip);
            using (DataReader dr = ExecuteReader(sql, search.Parameters))
            {
                dr.Skip(skip);
                return dr.ReadEntityArray<O>(search.PageSize);
            }
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据读取器</returns>
        public List<O> ExecuteEntityArray<O>(C connection, PS search) where O : BaseEntity, new()
        {
            search.TotalCount = ExecuteScalar(connection, CreateCountSql(search), search.Parameters).IntValue;
            int skip;
            string sql = CreatePageSql(search, Provider, version, out skip);
            using (DataReader dr = ExecuteReader(connection, sql, search.Parameters))
            {
                dr.Skip(skip);
                return dr.ReadEntityArray<O>(search.PageSize);
            }
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据读取器
        /// </summary>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据读取器</returns>
        public List<O> ExecuteEntityArray<O>(T transaction, PS search) where O : BaseEntity, new()
        {
            search.TotalCount = ExecuteScalar(transaction, CreateCountSql(search), search.Parameters).IntValue;
            int skip;
            string sql = CreatePageSql(search, Provider, version, out skip);
            using (DataReader dr = ExecuteReader(transaction, sql, search.Parameters))
            {
                dr.Skip(skip);
                return dr.ReadEntityArray<O>(search.PageSize);
            }
        }
        #endregion

        #region 执行SQL命令，返回一个实体

        #region 构造函数不带参数
        /// <summary>
        /// 读取一个对象，如果没有查到，返回null
        /// </summary>
        /// <typeparam name="O">对象类型</typeparam>
        /// <param name="commandText">SQL脚本</param>
        /// <returns></returns>
        public O ExecuteEntity<O>(string commandText) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(commandText))
            {
                return dr.ReadEntity<O>();
            }
        }
        /// <summary>
        /// 读取一个对象，如果没有查到，返回null
        /// </summary>
        /// <typeparam name="O">对象类型</typeparam>
        /// <param name="commandText">SQL脚本</param>
        /// <returns></returns>
        public O ExecuteEntity<O>(C connection, string commandText) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(connection, commandText))
            {
                return dr.ReadEntity<O>();
            }
        }
        public O ExecuteEntity<O>(T transaction, string commandText) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(transaction, commandText))
            {
                return dr.ReadEntity<O>();
            }
        }
        public O ExecuteEntity<O>(string commandText, params P[] commandParameters) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(commandText, commandParameters))
            {
                return dr.ReadEntity<O>();
            }
        }
        public O ExecuteEntity<O>(C connection, string commandText, params P[] commandParameters) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(connection, commandText, commandParameters))
            {
                return dr.ReadEntity<O>();
            }
        }
        public O ExecuteEntity<O>(T transaction, string commandText, params P[] commandParameters) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(transaction, commandText, commandParameters))
            {
                return dr.ReadEntity<O>();
            }
        }
        public O ExecuteEntity<O>(DataCommand<P> command) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(command))
            {
                return dr.ReadEntity<O>();
            }
        }
        public O ExecuteEntity<O>(C connection, DataCommand<P> command) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(connection, command))
            {
                return dr.ReadEntity<O>();
            }
        }
        public O ExecuteEntity<O>(T transaction, DataCommand<P> command) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(transaction, command))
            {
                return dr.ReadEntity<O>();
            }
        }
        #endregion

        #region 构造函数带有参数
        public O ExecuteEntity<O>(string commandText, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(commandText))
            {
                return dr.ReadEntity<O>(args);
            }
        }
        public O ExecuteEntity<O>(C connection, string commandText, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(connection, commandText))
            {
                return dr.ReadEntity<O>(args);
            }
        }
        public O ExecuteEntity<O>(T transaction, string commandText, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(transaction, commandText))
            {
                return dr.ReadEntity<O>(args);
            }
        }
        public O ExecuteEntity<O>(string commandText, object[] args, params P[] commandParameters) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(commandText, commandParameters))
            {
                return dr.ReadEntity<O>(args);
            }
        }
        public O ExecuteEntity<O>(C connection, string commandText, object[] args, params P[] commandParameters) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(connection, commandText, commandParameters))
            {
                return dr.ReadEntity<O>(args);
            }
        }
        public O ExecuteEntity<O>(T transaction, string commandText, object[] args, params P[] commandParameters) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(transaction, commandText, commandParameters))
            {
                return dr.ReadEntity<O>(args);
            }
        }
        public O ExecuteEntity<O>(DataCommand<P> command, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(command))
            {
                return dr.ReadEntity<O>(args);
            }
        }
        public O ExecuteEntity<O>(C connection, DataCommand<P> command, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(connection, command))
            {
                return dr.ReadEntity<O>(args);
            }
        }
        public O ExecuteEntity<O>(T transaction, DataCommand<P> command, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(transaction, command))
            {
                return dr.ReadEntity<O>(args);
            }
        }
        #endregion

        #region 返回数组，构造函数不带参数
        /// <summary>
        /// 读取对象数组
        /// </summary>
        /// <typeparam name="O"></typeparam>
        /// <param name="commandText"></param>
        /// <param name="ps"></param>
        /// <returns></returns>
        public List<O> ExecuteEntityArray<O>(string commandText) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(commandText))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>());
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(C connection, string commandText) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(connection, commandText))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>());
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(T transaction, string commandText) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(transaction, commandText))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>());
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(string commandText, params P[] commandParameters) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(commandText, commandParameters))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>());
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(C connection, string commandText, params P[] commandParameters) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(connection, commandText, commandParameters))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>());
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(T transaction, string commandText, params P[] commandParameters) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(transaction, commandText, commandParameters))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>());
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(DataCommand<P> command) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(command))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>());
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(C connection, DataCommand<P> command) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(connection, command))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>());
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(T transaction, DataCommand<P> command) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(transaction, command))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>());
                return result;
            }
        }
        #endregion

        #region 返回数组，构造函数带参数
        /// <summary>
        /// 读取对象数组
        /// </summary>
        /// <typeparam name="O"></typeparam>
        /// <param name="commandText"></param>
        /// <param name="ps"></param>
        /// <returns></returns>
        public List<O> ExecuteEntityArray<O>(string commandText, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(commandText))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>(args));
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(C connection, string commandText, object[] args) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(connection, commandText))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>(args));
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(T transaction, string commandText, object[] args) where O : BaseEntity, new()
        {
            using (DataReader dr = ExecuteReader(transaction, commandText))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>(args));
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(string commandText, object[] args, params P[] commandParameters) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(commandText, commandParameters))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>(args));
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(C connection, string commandText, object[] args, params P[] commandParameters) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(connection, commandText, commandParameters))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>(args));
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(T transaction, string commandText, object[] args, params P[] commandParameters) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(transaction, commandText, commandParameters))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>(args));
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(DataCommand<P> command, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(command))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>(args));
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(C connection, DataCommand<P> command, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(connection, command))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>(args));
                return result;
            }
        }
        public List<O> ExecuteEntityArray<O>(T transaction, DataCommand<P> command, object[] args) where O : BaseEntity
        {
            using (DataReader dr = ExecuteReader(transaction, command))
            {
                List<O> result = new List<O>(dr.ReadEntityArray<O>(args));
                return result;
            }
        }
        #endregion

        #region 执行数据库命令,返回结果的第一行第一列

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(string commandText)
        {
            return ExecuteScalar(commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库存储过程,返回结果的第一行第一列
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(string commandText, params object[] ps)
        {
            P[] pvs = GrabParameters(commandText);
            if (pvs == null)
            {
                pvs = GetProcParameters(commandText);
            }
            for (int i = 0; i < pvs.Length && i < ps.Length; i++)
            {
                pvs[i].Value = ps[i];
            }
            return ExecuteScalar(commandText, CommandType.StoredProcedure, pvs);
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(C connection, string commandText)
        {
            return ExecuteScalar(connection, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(T transaction, string commandText)
        {
            return ExecuteScalar(transaction, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(string commandText, params P[] commandParameters)
        {
            return ExecuteScalar(commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(C connection, string commandText, params P[] commandParameters)
        {
            return ExecuteScalar(connection, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(T transaction, string commandText, params P[] commandParameters)
        {
            return ExecuteScalar(transaction, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (C cn = CreateConnection())
            {
                return ExecuteScalar(cn, commandText, commandType, commandParameters);
            }
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(C connection, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = connection.CreateCommand())
            {
                using (var dr = ExecuteReader(connection, commandText, commandType, commandParameters))
                {
                    return new ScalerResult(dr.Read() ? dr[0] : PTA.Convert.DBNull, cmd, this);
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(T transaction, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                using (var dr = ExecuteReader(transaction, commandText, commandType, commandParameters))
                {
                    return new ScalerResult(dr.Read() ? dr[0] : PTA.Convert.DBNull, cmd, this);
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="command">数据库命令</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(DataCommand<P> command)
        {
            return ExecuteScalar(command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="command">数据库命令</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(C connection, DataCommand<P> command)
        {
            return ExecuteScalar(connection, command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回结果的第一行第一列
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="connection">数据库连接对象</param>
        /// <returns>返回结果的第一行第一列</returns>
        public ScalerResult ExecuteScalar(T transaction, DataCommand<P> command)
        {
            return ExecuteScalar(transaction, command.CommandText, command.CommandType, command.Parameters);
        }


        #endregion 执行数据库命令,返回结果的第一行第一列
        #endregion

        #region 执行数据库命令,返回一个DataReader

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(string commandText)
        {
            return ExecuteReader(commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库存储过程,返回一个数据读取器
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(string commandText, params object[] ps)
        {
            P[] pvs = GrabParameters(commandText);
            if (pvs == null)
            {
                pvs = GetProcParameters(commandText);
            }
            for (int i = 0; i < pvs.Length && i < ps.Length; i++)
            {
                pvs[i].Value = ps[i];
            }
            return ExecuteReader(commandText, CommandType.StoredProcedure, pvs);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(C connection, string commandText)
        {
            return ExecuteReader(connection, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(T transaction, string commandText)
        {
            return ExecuteReader(transaction, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(C connection, PS search, params P[] commandParameters)
        {
            search.TotalCount = ExecuteScalar(connection, CreateCountSql(search), CommandType.Text, commandParameters).IntValue;
            int skip;
            string sql = CreatePageSql(search, Provider, version, out skip);
            DataReader dr = ExecuteReader(connection, sql, commandParameters);
            dr.Skip(skip);
            return dr;
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据读取器
        /// </summary>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="search">查询条件</param>
        /// <param name="commandParameters">数据库命令类型</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(T transaction, PS search, params P[] commandParameters)
        {
            search.TotalCount = ExecuteScalar(transaction, CreateCountSql(search), CommandType.Text, commandParameters).IntValue;
            int skip;
            string sql = CreatePageSql(search, Provider, version, out skip);
            DataReader dr = ExecuteReader(transaction, sql, commandParameters);
            dr.Skip(skip);
            return dr;
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据读取器
        /// </summary>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="search">查询条件</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(T transaction, PS search, CommandType commandType, params P[] commandParameters)
        {
            search.TotalCount = ExecuteScalar(transaction, CreateCountSql(search), CommandType.Text, commandParameters).IntValue;
            int skip;
            string sql = CreatePageSql(search, Provider, version, out skip);
            DataReader dr = ExecuteReader(transaction, sql, commandType, commandParameters);
            dr.Skip(skip);
            return dr;
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(string commandText, params P[] commandParameters)
        {
            return ExecuteReader(commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(C connection, string commandText, params P[] commandParameters)
        {
            return ExecuteReader(connection, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(T transaction, string commandText, params P[] commandParameters)
        {
            return ExecuteReader(transaction, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(DataCommand<P> command)
        {
            return ExecuteReader(command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(C connection, DataCommand<P> command)
        {
            return ExecuteReader(connection, command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(T transaction, DataCommand<P> command)
        {
            return ExecuteReader(transaction, command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <param name="connectionOwnership">数据库命令的连接类型</param>
        /// <returns>返回一个数据读取器</returns>
        private DataReader ExecuteReader(C connection, T transaction, string commandText, CommandType commandType, P[] commandParameters, ConnOwnerShip connectionOwnership)
        {
            IDbCommand cmd = connection.CreateCommand();
            PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters);
            try
            {
                if (connectionOwnership == ConnOwnerShip.External)
                {
                    return new DataReader(cmd.ExecuteReader(), cmd, this);
                }
                else
                {
                    return new DataReader(cmd.ExecuteReader(CommandBehavior.CloseConnection), cmd, this);
                }
            }
            catch (Exception ex)
            {
                connection.Close();
                throw new DataBaseException(WriteDbException(ex, cmd));
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(string commandText, CommandType commandType, params P[] commandParameters)
        {
            C connection = this.CreateConnection();
            return ExecuteReader(connection, null, commandText, commandType, commandParameters, ConnOwnerShip.Internal);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(C connection, string commandText, CommandType commandType, params P[] commandParameters)
        {
            return ExecuteReader(connection, null, commandText, commandType, commandParameters, ConnOwnerShip.External);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据读取器
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据读取器</returns>
        public DataReader ExecuteReader(T transaction, string commandText, CommandType commandType, params P[] commandParameters)
        {
            return ExecuteReader((C)transaction.Connection, transaction, commandText, commandType, commandParameters, ConnOwnerShip.External);
        }

        #endregion  执行数据库命令,返回一个DataReader

        #region 执行数据库命令,返回一个数据表

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(string commandText)
        {
            return ExecuteDataTable(commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库存储过程,返回一个数据表
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(string commandText, params object[] ps)
        {
            P[] pvs = GrabParameters(commandText);
            if (pvs == null)
            {
                pvs = GetProcParameters(commandText);
            }
            for (int i = 0; i < pvs.Length && i < ps.Length; i++)
            {
                pvs[i].Value = ps[i];
            }
            return ExecuteDataTable(commandText, CommandType.StoredProcedure, pvs);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(C connection, string commandText)
        {
            return ExecuteDataTable(connection, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(T transaction, string commandText)
        {
            return ExecuteDataTable(transaction, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据表
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(PS search)
        {
            using (C conn = this.CreateConnection())
            {
                return ExecuteDataTable(conn, search);
            }
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据表
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(PS search, params P[] commandParameters)
        {
            using (C conn = this.CreateConnection())
            {
                return ExecuteDataTable(conn, search, commandParameters);
            }
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据表
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(C connection, PS search)
        {
            using (DataReader dr = ExecuteReader(connection, search))
            {
                DataTable dt = new DataTable();
                dt.Load(dr.OriDataReader);
                return new DataTableResult(dt, dr.CommandText, dr.CommandType, dr.Parameters);
            }
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据表
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="search">查询条件</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(C connection, PS search, params P[] commandParameters)
        {
            using (DataReader dr = ExecuteReader(connection, search, commandParameters))
            {
                DataTable dt = new DataTable();
                dt.Load(dr.OriDataReader);
                return new DataTableResult(dt, dr.CommandText, dr.CommandType, dr.Parameters);
            }
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据表
        /// </summary>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="search">查询条件</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(T transaction, PS search)
        {
            using (DataReader dr = ExecuteReader(transaction, search))
            {
                DataTable dt = new DataTable();
                dt.Load(dr.OriDataReader);
                return new DataTableResult(dt, dr.CommandText, dr.CommandType, dr.Parameters);
            }
        }

        /// <summary>
        /// 执行SQL语句,返回一个数据表
        /// </summary>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="search">查询条件</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(T transaction, PS search, params P[] commandParameters)
        {
            using (DataReader dr = ExecuteReader(transaction, search, commandParameters))
            {
                DataTable dt = new DataTable();
                dt.Load(dr.OriDataReader);
                return new DataTableResult(dt, dr.CommandText, dr.CommandType, dr.Parameters);
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(string commandText, params P[] commandParameters)
        {
            return ExecuteDataTable(commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(C connection, string commandText, params P[] commandParameters)
        {
            return ExecuteDataTable(connection, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(T transaction, string commandText, params P[] commandParameters)
        {
            return ExecuteDataTable(transaction, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (C connection = this.CreateConnection())
            {
                return ExecuteDataTable(connection, commandText, commandType, commandParameters);
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(C connection, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = connection.CreateCommand())
            {
                PrepareCommand(cmd, connection, null, commandType, commandText, commandParameters);
                A da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                da.SelectCommand = cmd;
                try
                {
                    if (da is DbDataAdapter)
                    {
                        using (da as IDisposable)
                        {
                            DataTable dt = new DataTable();
                            (da as DbDataAdapter).Fill(dt);
                            return new DataTableResult(dt, cmd, this);
                        }
                    }
                    else
                    {
                        using (da as IDisposable)
                        {
                            DataSet ds = new DataSet();
                            da.Fill(ds);
                            return new DataTableResult(ds.Tables[0], cmd, this);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(T transaction, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
                A da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                using (da as IDisposable)
                {
                    da.SelectCommand = cmd;
                    try
                    {
                        if (da is DbDataAdapter)
                        {
                            using (da as IDisposable)
                            {
                                DataTable dt = new DataTable();
                                (da as DbDataAdapter).Fill(dt);
                                return new DataTableResult(dt, cmd, this);
                            }
                        }
                        else
                        {
                            using (da as IDisposable)
                            {
                                DataSet ds = new DataSet();
                                da.Fill(ds);
                                return new DataTableResult(ds.Tables[0], cmd, this);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new DataBaseException(WriteDbException(ex, cmd));
                    }
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(DataCommand<P> command)
        {
            return ExecuteDataTable(command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(C connection, DataCommand<P> command)
        {
            return ExecuteDataTable(connection, command.CommandText, command.CommandType, command.Parameters);
        }
        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult ExecuteDataTable(T transaction, DataCommand<P> command)
        {
            return ExecuteDataTable(transaction, command.CommandText, command.CommandType, command.Parameters);
        }
        #endregion 执行数据库命令,返回一个数据表

        #region 执行数据库命令,填充一个数据表

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="dt">要填充的数据表</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, string commandText)
        {
            return Fill(dt, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, C connection, string commandText)
        {
            return Fill(dt, connection, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, T transaction, string commandText)
        {
            return Fill(dt, transaction, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, string commandText, params P[] commandParameters)
        {
            return Fill(dt, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, C connection, string commandText, params P[] commandParameters)
        {
            return Fill(dt, connection, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, T transaction, string commandText, params P[] commandParameters)
        {
            return Fill(dt, transaction, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (C connection = this.CreateConnection())
            {
                return Fill(dt, connection, commandText, commandType, commandParameters);
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, DataCommand<P> command)
        {
            return Fill(dt, command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, C connection, DataCommand<P> command)
        {
            return Fill(dt, connection, command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, T transaction, DataCommand<P> command)
        {
            return Fill(dt, transaction, command.CommandText, command.CommandType, command.Parameters);
        }
        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, C connection, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = connection.CreateCommand())
            {
                PrepareCommand(cmd, connection, null, commandType, commandText, commandParameters);
                A da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                da.SelectCommand = cmd;
                try
                {
                    if (da is DbDataAdapter)
                    {
                        using (da as IDisposable)
                        {
                            (da as DbDataAdapter).Fill(dt);
                            return new DataTableResult(dt, cmd, this);
                        }
                    }
                    throw new Exception("不支持当前DataAdapter类型,具体类型为:" + da.GetType().FullName);
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据表
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="dt">要填充的数据表</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据表</returns>
        public DataTableResult Fill(DataTable dt, T transaction, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
                A da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                da.SelectCommand = cmd;
                try
                {
                    if (da is DbDataAdapter)
                    {
                        using (da as IDisposable)
                        {
                            (da as DbDataAdapter).Fill(dt);
                            return new DataTableResult(dt, cmd, this);
                        }
                    }
                    throw new Exception("不支持当前DataAdapter类型,具体类型为:" + da.GetType().FullName);
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }

        #endregion 执行数据库命令,返回一个数据表

        #region 执行数据库命令,返回一个数据集

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(string commandText)
        {
            return ExecuteDataSet(commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库存储过程,返回一个数据集
        /// </summary>
        /// <param name="commandText">数据库存储过程命令</param>
        /// <param name="ps">参数的值列表</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(string commandText, params object[] ps)
        {
            P[] pvs = GrabParameters(commandText);
            if (pvs == null)
            {
                pvs = GetProcParameters(commandText);
            }
            for (int i = 0; i < pvs.Length && i < ps.Length; i++)
            {
                pvs[i].Value = ps[i];
            }
            return ExecuteDataSet(commandText, CommandType.StoredProcedure, pvs);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(C connection, string commandText)
        {
            return ExecuteDataSet(connection, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(T transaction, string commandText)
        {
            return ExecuteDataSet(transaction, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(string commandText, params P[] commandParameters)
        {
            return ExecuteDataSet(commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(C connection, string commandText, params P[] commandParameters)
        {
            return ExecuteDataSet(connection, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(T transaction, string commandText, params P[] commandParameters)
        {
            return ExecuteDataSet(transaction, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (C cn = this.CreateConnection())
            {
                return ExecuteDataSet(cn, commandText, commandType, commandParameters);
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(C connection, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = connection.CreateCommand())
            {
                PrepareCommand(cmd, connection, null, commandType, commandText, commandParameters);
                A da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                da.SelectCommand = cmd;
                try
                {
                    if (da is DbDataAdapter)
                    {
                        using (da as IDisposable)
                        {
                            DataSet ds = new DataSet();
                            da.Fill(ds);
                            return new DataSetResult(ds, cmd, this);
                        }
                    }
                    throw new Exception("不支持当前DataAdapter类型,具体类型为:" + da.GetType().FullName);
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(T transaction, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
                A da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                da.SelectCommand = cmd;
                try
                {
                    if (da is DbDataAdapter)
                    {
                        using (da as IDisposable)
                        {
                            DataSet ds = new DataSet();
                            da.Fill(ds);
                            return new DataSetResult(ds, cmd, this);
                        }
                    }
                    throw new Exception("不支持当前DataAdapter类型,具体类型为:" + da.GetType().FullName);
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(DataCommand<P> command)
        {
            return ExecuteDataSet(command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(C connection, DataCommand<P> command)
        {
            return ExecuteDataSet(connection, command.CommandText, command.CommandType, command.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,返回一个数据集
        /// </summary>
        /// <param name="transaction">数据库事务对象</param>
        /// <param name="command">数据库命令</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult ExecuteDataSet(T transaction, DataCommand<P> command)
        {
            return ExecuteDataSet(transaction, command.CommandText, command.CommandType, command.Parameters);
        }
        #endregion 执行数据库命令,返回一个数据集

        #region 执行数据库命令,填充一个数据集

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="cmd">数据库命令的文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, DataCommand<P> cmd)
        {
            return Fill(ds, cmd.CommandText, cmd.CommandType, cmd.Parameters);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string commandText)
        {
            return Fill(ds, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="connection">数据库连接</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, C connection, string commandText)
        {
            return Fill(ds, connection, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, T transaction, string commandText)
        {
            return Fill(ds, transaction, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string commandText, params P[] commandParameters)
        {
            return Fill(ds, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="connection">数据库连接</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, C connection, string commandText, params P[] commandParameters)
        {
            return Fill(ds, connection, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, T transaction, string commandText, params P[] commandParameters)
        {
            return Fill(ds, transaction, commandText, GuessCommandType(commandText), commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="commandType">数据库命令的类型</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (C connection = this.CreateConnection())
            {
                return Fill(ds, connection, commandText, commandType, commandParameters);
            }
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="connection">数据库连接</param>
        /// <param name="commandType">数据库命令的类型</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, C connection, string commandText, CommandType commandType, params P[] commandParameters)
        {
            if (ds == null)
            {
                throw new Exception("要填充的数据集不能为空");
            }
            using (IDbCommand cmd = connection.CreateCommand())
            {
                PrepareCommand(cmd, connection, null, commandType, commandText, commandParameters);
                IDbDataAdapter da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                da.SelectCommand = cmd;
                {
                    try
                    {
                        if (da is DbDataAdapter)
                        {
                            using (da as IDisposable)
                            {
                                da.Fill(ds);
                                return new DataSetResult(ds, cmd, this);
                            }
                        }
                        throw new Exception("不支持当前DataAdapter类型,具体类型为:" + da.GetType().FullName);
                    }
                    catch (Exception ex)
                    {
                        throw new DataBaseException(WriteDbException(ex, cmd));
                    }
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="commandType">数据库命令的类型</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, T transaction, string commandText, CommandType commandType, params P[] commandParameters)
        {
            if (ds == null)
            {
                throw new Exception("要填充的数据集不能为空");
            }
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
                IDbDataAdapter da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                da.SelectCommand = cmd;
                {
                    try
                    {
                        if (da is DbDataAdapter)
                        {
                            using (da as IDisposable)
                            {
                                da.Fill(ds);
                                return new DataSetResult(ds, cmd, this);
                            }
                        }
                        throw new Exception("不支持当前DataAdapter类型,具体类型为:" + da.GetType().FullName);
                    }
                    catch (Exception ex)
                    {
                        throw new DataBaseException(WriteDbException(ex, cmd));
                    }
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="srcTable">要填充的数据集的表的名称</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string srcTable, string commandText)
        {
            return Fill(ds, srcTable, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="srcTable">要填充的数据集的表的名称</param>
        /// <param name="connection">数据库连接</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string srcTable, C connection, string commandText)
        {
            return Fill(ds, srcTable, connection, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="srcTable">要填充的数据集的表的名称</param>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string srcTable, T transaction, string commandText)
        {
            return Fill(ds, srcTable, transaction, commandText, CommandType.Text, null);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="srcTable">要填充的数据集的表的名称</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string srcTable, string commandText, params P[] commandParameters)
        {
            return Fill(ds, srcTable, commandText, CommandType.StoredProcedure, commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="srcTable">要填充的数据集的表的名称</param>
        /// <param name="connection">数据库连接</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string srcTable, C connection, string commandText, params P[] commandParameters)
        {
            return Fill(ds, srcTable, connection, commandText, CommandType.StoredProcedure, commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="srcTable">要填充的数据集的表的名称</param>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string srcTable, T transaction, string commandText, params P[] commandParameters)
        {
            return Fill(ds, srcTable, transaction, commandText, CommandType.StoredProcedure, commandParameters);
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="srcTable">要填充的数据集的表的名称</param>
        /// <param name="commandType">数据库命令的类型</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string srcTable, string commandText, CommandType commandType, params P[] commandParameters)
        {
            using (C connection = this.CreateConnection())
            {
                return Fill(ds, srcTable, connection, commandText, commandType, commandParameters);
            }
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="srcTable">要填充的数据集的表的名称</param>
        /// <param name="connection">数据库连接</param>
        /// <param name="commandType">数据库命令的类型</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string srcTable, C connection, string commandText, CommandType commandType, params P[] commandParameters)
        {
            if (ds == null)
            {
                throw new Exception("要填充的数据集不能为空");
            }
            using (IDbCommand cmd = connection.CreateCommand())
            {
                PrepareCommand(cmd, connection, null, commandType, commandText, commandParameters);
                IDbDataAdapter da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                da.SelectCommand = cmd;
                {
                    try
                    {
                        if (da is DbDataAdapter)
                        {
                            using (da as IDisposable)
                            {
                                (da as DbDataAdapter).Fill(ds, srcTable);
                                return new DataSetResult(ds, cmd, this);
                            }
                        }
                        throw new Exception("不支持当前DataAdapter类型,具体类型为:" + da.GetType().FullName);
                    }
                    catch (Exception ex)
                    {
                        throw new DataBaseException(WriteDbException(ex, cmd));
                    }
                }
            }
        }

        /// <summary>
        /// 执行数据库命令,填充一个数据集
        /// </summary>
        /// <param name="ds">要填充的数据集</param>
        /// <param name="srcTable">要填充的数据集的表的名称</param>
        /// <param name="transaction">数据库连接上的事务</param>
        /// <param name="commandType">数据库命令的类型</param>
        /// <param name="commandText">数据库命令的文本</param>
        /// <param name="commandParameters">数据库命令的参数</param>
        /// <returns>返回一个数据集</returns>
        public DataSetResult Fill(DataSet ds, string srcTable, T transaction, string commandText, CommandType commandType, params P[] commandParameters)
        {
            if (ds == null)
            {
                throw new Exception("要填充的数据集不能为空");
            }
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters);
                IDbDataAdapter da = typeof(A).Assembly.CreateInstance(typeof(A).FullName) as A;
                da.SelectCommand = cmd;
                try
                {
                    if (da is DbDataAdapter)
                    {
                        using (da as IDisposable)
                        {
                            (da as DbDataAdapter).Fill(ds, srcTable);
                            return new DataSetResult(ds, cmd, this);
                        }
                    }
                    throw new Exception("不支持当前DataAdapter类型,具体类型为:" + da.GetType().FullName);
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }
        #endregion

        #region 执行事务

        /// <summary>
        /// 执行一系列的事务
        /// </summary>
        /// <param name="commands">数据库命令</param>
        public int ExecuteTransaction(IList<string> commands)
        {
            using (C conn = this.CreateConnection())
            {
                return ExecuteTransaction(conn, commands);
            }
        }

        /// <summary>
        /// 执行一系列的事务
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commands">数据库命令</param>
        public int ExecuteTransaction(C connection, IList<string> commands)
        {
            if (commands == null || commands.Count == 0)
            {
                return 0;
            }
            bool connisopen = true;
            if (connection.State != ConnectionState.Open)
            {
                connisopen = false;
                connection.Open();
            }

            using (IDbCommand cmd = connection.CreateCommand())
            using (T trans = (T)connection.BeginTransaction())
            {
                try
                {
                    int r = ExecuteTransaction(trans, commands);
                    trans.Commit();
                    return r;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
                finally
                {
                    if (connisopen == false)
                    {
                        connection.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 在一个事务上执行SQL语句.执行完后不提交,出错后也不回滚,需要手动处理
        /// </summary>
        /// <param name="transaction">数据库事务</param>
        /// <param name="commands">要执行的命令列表</param>
        public int ExecuteTransaction(T transaction, IList<string> commands)
        {
            if (commands == null || commands.Count == 0)
            {
                return 0;
            }
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                try
                {
                    int r = 0;
                    foreach (string command in commands)
                    {
                        PrepareCommand(cmd, transaction.Connection, transaction, CommandType.Text, command, null);
                        r = cmd.ExecuteNonQuery();
                    }
                    return r;
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }

        /// <summary>
        /// 执行一系列的事务
        /// </summary>
        /// <param name="commands">数据库命令</param>
        public int ExecuteTransaction(IList<DataCommand<P>> commands)
        {
            using (C conn = this.CreateConnection())
            {
                return ExecuteTransaction(conn, commands);
            }
        }

        /// <summary>
        /// 执行一系列的事务
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commands">数据库命令</param>
        public int ExecuteTransaction(C connection, IList<DataCommand<P>> commands)
        {
            if (commands == null || commands.Count == 0)
            {
                return 0;
            }
            bool connisopen = true;
            if (connection.State != ConnectionState.Open)
            {
                connisopen = false;
                connection.Open();
            }

            using (T trans = (T)connection.BeginTransaction())
            {
                try
                {
                    int r = ExecuteTransaction(trans, commands);
                    trans.Commit();
                    return r;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
                finally
                {
                    if (connisopen == false)
                    {
                        connection.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 在一个事务上执行SQL语句.执行完后不提交,出错后也不回滚,需要手动处理
        /// </summary>
        /// <param name="transaction">数据库事务</param>
        /// <param name="commands">要执行的命令列表</param>
        public int ExecuteTransaction(T transaction, IList<DataCommand<P>> commands)
        {
            if (commands == null || commands.Count == 0)
            {
                return 0;
            }
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                try
                {
                    int r = 0;
                    foreach (DataCommand<P> command in commands)
                    {
                        PrepareCommand(cmd, transaction.Connection, transaction, command.CommandType, command.CommandText, command.Parameters);
                        r = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                    }
                    return r;
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }

        #endregion

        #region 执行事务,最后返回一个ScalerResult对象

        /// <summary>
        /// 执行一系列的事务,最后一个SQL命令返回Scaler对象
        /// </summary>
        /// <param name="commands">数据库命令</param>
        public ScalerResult ExecuteScalerTransaction(IList<string> commands)
        {
            using (C conn = this.CreateConnection())
            {
                return ExecuteScalerTransaction(conn, commands);
            }
        }

        /// <summary>
        /// 执行一系列的事务,最后一个SQL命令返回Scaler对象
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commands">数据库命令</param>
        public ScalerResult ExecuteScalerTransaction(C connection, IList<string> commands)
        {
            ScalerResult result = null;
            if (commands == null || commands.Count == 0)
            {
                return result;
            }
            bool connisopen = true;
            if (connection.State != ConnectionState.Open)
            {
                connisopen = false;
                connection.Open();
            }
            using (T trans = (T)connection.BeginTransaction())
            {
                try
                {
                    ScalerResult r = ExecuteScalerTransaction(trans, commands);
                    trans.Commit();
                    return r;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
                finally
                {
                    if (connisopen == false)
                    {
                        connection.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 在一个事务上执行SQL语句.执行完后不提交,出错后也不回滚,需要手动处理
        /// </summary>
        /// <param name="transaction">数据库事务</param>
        /// <param name="commands">要执行的命令列表</param>
        public ScalerResult ExecuteScalerTransaction(T transaction, IList<string> commands)
        {
            if (commands == null || commands.Count == 0)
            {
                return null;
            }
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                try
                {
                    string lastsql = commands[commands.Count - 1];
                    commands.RemoveAt(commands.Count - 1);
                    foreach (string command in commands)
                    {
                        PrepareCommand(cmd, transaction.Connection, transaction, CommandType.Text, command, null);
                        cmd.ExecuteNonQuery();
                    }
                    return ExecuteScalar(transaction, lastsql);
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }

        /// <summary>
        /// 执行一系列的事务,最后一个SQL命令返回Scaler对象
        /// </summary>
        /// <param name="commands">数据库命令</param>
        public ScalerResult ExecuteScalerTransaction(IList<DataCommand<P>> commands)
        {
            using (C conn = this.CreateConnection())
            {
                return ExecuteScalerTransaction(conn, commands);
            }
        }

        /// <summary>
        /// 执行一系列的事务,最后一个SQL命令返回Scaler对象
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="commands">数据库命令</param>
        public ScalerResult ExecuteScalerTransaction(C connection, IList<DataCommand<P>> commands)
        {
            if (commands == null || commands.Count == 0)
            {
                return null;
            }
            bool connisopen = true;
            if (connection.State != ConnectionState.Open)
            {
                connisopen = false;
                connection.Open();
            }

            using (T trans = (T)connection.BeginTransaction())
            {
                try
                {
                    ScalerResult r = ExecuteScalerTransaction(trans, commands);
                    trans.Commit();
                    return r;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
                finally
                {
                    if (connisopen == false)
                    {
                        connection.Close();
                    }
                }
            }
        }

        /// <summary>
        /// 在一个事务上执行SQL语句.执行完后不提交,出错后也不回滚,需要手动处理
        /// </summary>
        /// <param name="transaction">数据库事务</param>
        /// <param name="commands">要执行的命令列表</param>
        public ScalerResult ExecuteScalerTransaction(T transaction, IList<DataCommand<P>> commands)
        {
            if (commands == null || commands.Count == 0)
            {
                return null;
            }
            using (IDbCommand cmd = transaction.Connection.CreateCommand())
            {
                try
                {
                    DataCommand<P> lastsql = commands[commands.Count - 1];
                    commands.RemoveAt(commands.Count - 1);
                    foreach (DataCommand<P> command in commands)
                    {
                        PrepareCommand(cmd, transaction.Connection, transaction, command.CommandType, command.CommandText, command.Parameters);
                        cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                    }
                    return ExecuteScalar(transaction, lastsql.CommandText, lastsql.CommandType, lastsql.Parameters);
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
            }
        }
        #endregion

        #region 格式化数据

        public string ToSqlValue(object value)
        {
            string result = string.Empty;
            if (value == null || value == DBNull.Value)
            {
                return "NULL";
            }
            if (value is int || value is long || value is short || value is byte || value is double || value is float)
            {
                return value.ToString();
            }
            if (value is DateTime)
            {
                if ((DateTime)value == DateTime.MinValue || (DateTime)value == DateTime.MaxValue)
                {
                    return "NULL";
                }
                result = string.Format("'{0}'", ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss.fff")); ;
                switch (provider)
                {
                    case DbProvider.Oracle:
                        {
                            result = string.Format("to_date('{0}','YYYY-MM-DD HH24:MI:SS')", ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"));
                            break;
                        }
                    case DbProvider.OleDb:
                        {
                            result = ((DateTime)value).ToString("#yyyy-MM-dd HH:mm:ss#");
                            break;
                        }
                }
                return result;
            }
            if (value is TimeSpan)
            {
                if (((TimeSpan)value) == TimeSpan.Zero)
                {
                    return "NULL";
                }
                return ((TimeSpan)value).TotalSeconds.ToString();
            }
            if (value is string)
            {
                return string.Format("'{0}'", ((string)value).Replace("'", "''"));
            }
            if (value is bool)
            {
                return (bool)value ? "1" : "0";
            }
            if (value is Guid)
            {
                if (((Guid)value) == Guid.Empty)
                {
                    return "NULL";
                }
                return "'" + ((Guid)value).ToString() + "'";
            }
            if (value is Enum)
            {
                return ((int)value).ToString();
            }
            if (value is int[] || value is List<int>)
            {
                return string.Format("'{0}'", PTA.Convert.ToStrictString<int>((IEnumerable<int>)value, 0, 0));
            }
            if (value is long[] || value is List<long>)
            {
                return string.Format("'{0}'", PTA.Convert.ToStrictString<long>((IEnumerable<long>)value, 0, 0));
            }
            if (value is string[] || value is List<string>)
            {
                return string.Format("'{0}'", PTA.Convert.ToStrictString<string>((IEnumerable<string>)value, 0, 0).Replace("'", "''"));
            }
            if (result.Length == 0)
            {
                throw new Exception("数据类型映射为数据库类型时错误");
            }
            return result;
        }

        /// <summary>
        /// 返回一个为字符串两边加上%的字符串
        /// </summary>
        /// <param name="value">原始字符串</param>
        /// <returns>格式化后的字符串</returns>
        public string ToLikeValue(string value)
        {
            if (value == null)
            {
                value = string.Empty;
            }
            return string.Format("'%{0}%'", value.Replace("'", "''"));
        }

        /// <summary>
        /// 把一个整型列表创建一个IN表达式
        /// </summary>
        /// <param name="colume">列名</param>
        /// <param name="value">IN表达式的值列表</param>
        /// <returns>创建后的IN表达式</returns>
        public string BuildInSql<DT>(string colume, IEnumerable<DT> values, Func<DT, string> convert = null)
        {
            if (String.IsNullOrWhiteSpace(colume))
            {
                throw new Exception("列名不能为空.");
            }
            if (values == null)
            {
                throw new ArgumentNullException("value");
            }
            if (values.GetEnumerator().MoveNext())
            {
                StringBuilder sb = new StringBuilder("(");
                string join = values.JoinToString();
                sb.AppendFormat("{0} in ({1})", colume, join);
                sb.Append(")");
                return sb.ToString();

            }
            throw new Exception("要合并的列表长度不能为0.");
        }

        /// <summary>
        /// 把一个整型列表创建一个IN表达式
        /// </summary>
        /// <param name="colume">列名</param>
        /// <param name="length">IN表达式的最大长度(如Oracle最大长度为8000)</param>
        /// <param name="value">IN表达式的值列表</param>
        /// <returns>创建后的IN表达式</returns>
        public string BuildInSql<DT>(string colume, int length, IEnumerable<DT> value, Func<DT, string> convert = null)
        {
            if (length < 1)
            {
                throw new Exception("IN表达式的长度必须大于0");
            }
            int count = 0;
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            var itor = value.GetEnumerator();
            while (itor.MoveNext())
            {
                count++;
            }
            if (count == 0)
            {
                throw new Exception("要合并的列表长度不能为0.");
            }
            StringBuilder sb = new StringBuilder("(");
            string join = PTA.Convert.ToStrictString<DT>(value, 0, length, convert);
            sb.AppendFormat("{0} in ({1})", colume, join);
            if (length < count)
            {
                for (int i = length; i < count; i += length)
                {
                    join = PTA.Convert.ToStrictString<DT>(value, i, length, convert);
                    sb.AppendFormat(" OR {0} in ({1})", colume, join);
                }
            }
            sb.Append(")");
            return sb.ToString();
        }
        #endregion

        #region 实体插入更新删除获取
        /// <summary>
        /// 插入一个实体(要为实体的类名和属性名指定System.Data.Linq.Mapping.TableAttribute和System.Data.Linq.Mapping.ColumnAttribute)
        /// </summary>
        /// <param name="m"></param>
        public virtual void Insert(BaseEntity m)
        {
            var cmd = this.CreateCommand();
            EntityInfo ea = EntityHelper.GetEntityAttribute(m.GetType());
            StringBuilder insertsql = new StringBuilder(string.Format("INSERT INTO {0} (", ea.DataTable));
            bool hasfield = false;
            StringBuilder sbvalue = new StringBuilder("VALUES (");
            int pidx = 0;
            foreach (var item in ea.Properties.FindAll(p => ((p.Value.PropertyAttribute.Flag & BindingFlag.Insert) > 0) && (!p.Value.PropertyAttribute.Identity)))
            {
                insertsql.AppendFormat(hasfield ? ", {0}" : " {0}", item.Value.PropertyAttribute.Name);
                switch (item.Value.PropertyAttribute.DbType)
                {
                    case ColumnType.Json:
                        sbvalue.AppendFormat(hasfield ? ", {0}" : " {0}", cmd.AddIn("P" + pidx++, item.Value.PropertyInfo.GetValue(m, null).ToJson()).ParameterName);
                        break;
                    case ColumnType.Xml:
                        sbvalue.AppendFormat(hasfield ? ", {0}" : " {0}", cmd.AddIn("P" + pidx++, item.Value.PropertyInfo.GetValue(m, null).ToXml()).ParameterName);
                        break;
                    default:
                        object value = item.Value.PropertyInfo.GetValue(m, null);
                        value = (value is DateTime) ? ((DateTime)value == DateTime.MinValue ? null : value) : value;
                        sbvalue.AppendFormat(hasfield ? ", {0}" : " {0}", cmd.AddIn("P" + pidx++, value).ParameterName);
                        break;
                }
                hasfield = true;
            }
            insertsql.Append(" )").Append(sbvalue.ToString()).Append(" )").AppendLine();
            if (!hasfield)
            {
                throw new Exception(String.Format("没有为{0}类型的实体设置要插入数据库的字段", m.GetType().FullName));
            }
            switch (this.provider)
            {
                case DbProvider.SqlServer:
                case DbProvider.VistaDB:
                case DbProvider.MySql:
                    {
                        if (ea.Properties.Exists(item => item.Value.PropertyAttribute.Identity))
                        {
                            EntityPropertyInfo identityProperty = ea.Properties.Find(item => item.Value.PropertyAttribute.Identity).Value;
                            cmd.CommandText = insertsql.AppendLine().Append(" SELECT @@IDENTITY;").ToString();
                            identityProperty.PropertyInfo.SetValue(m, this.ExecuteScalar(cmd).IntValue, null);
                            return;
                        }
                        else
                        {
                            cmd.CommandText = insertsql.ToString();
                            this.ExecuteNonQuery(cmd);
                            return;
                        }
                    }
                default:
                    {
                        if (ea.Properties.Exists(item => !string.IsNullOrEmpty(item.Value.PropertyAttribute.SequenceName)))
                        {
                            //为标识为序列的属性创建值
                        }
                        else
                        {
                            cmd.CommandText = insertsql.ToString();
                        }
                        this.ExecuteNonQuery(cmd);
                        return;
                    }
            }
        }

        /// <summary>
        /// 更新一个实体(要为实体的类名和属性名指定System.Data.Linq.Mapping.TableAttribute和System.Data.Linq.Mapping.ColumnAttribute)
        /// </summary>
        /// <param name="m">返回一个值,指示影响的行数</param>
        public virtual int Update(BaseEntity m)
        {
            List<string> updates = (List<string>)Reflect.GetField<BaseEntity>(m, "updates", BindingFlags.NonPublic | BindingFlags.Instance);
            if (updates == null || updates.Count == 0)
            {
                return 0;
            }
            var cmd = this.CreateCommand();
            EntityInfo ea = EntityHelper.GetEntityAttribute(m.GetType());
            StringBuilder updatesql = new StringBuilder(string.Format("UPDATE {0} SET", ea.DataTable));

            int pidx = 0;
            bool hasfield = false;
            foreach (var proName in updates)
            {
                EntityPropertyInfo epi = ea.Properties[proName];
                if (((epi.PropertyAttribute.Flag & BindingFlag.Update) > 0) && (!epi.PropertyAttribute.Identity))
                {
                    updatesql.AppendFormat(hasfield ? ", {0} = {1}" : " {0} = {1}", epi.PropertyAttribute.Name, cmd.AddIn("P" + pidx++, epi.PropertyInfo.GetValue(m, null)).ParameterName);
                    hasfield = true;
                }
            }
            updatesql.AppendFormat(" WHERE");
            hasfield = false;
            foreach (var epi in ea.Properties.FindAll(p => p.Value.PropertyAttribute.PrimaryKey))
            {
                updatesql.AppendFormat(hasfield ? " AND {0} = {1}" : " {0} = {1}", epi.Value.PropertyAttribute.Name, cmd.AddIn("P" + pidx++, epi.Value.PropertyInfo.GetValue(m, null)).ParameterName);
                hasfield = true;
            }
            cmd.CommandText = updatesql.ToString();
            return this.ExecuteNonQuery(cmd).Value;
        }

        public string GetTable<E>() where E : BaseEntity
        {
            return EntityHelper.GetEntityAttribute(typeof(E)).DataTable;
        }
        #endregion

        #region 其它数据

        /// <summary>
        /// 指示要执行的数据库命令的数据库连接对象是来自于外部还是内部生成的
        /// </summary>
        internal enum ConnOwnerShip
        {
            /// <summary>
            /// 当DataReader关闭时,自动关闭数据连接对象
            /// </summary>
            Internal,

            /// <summary>
            /// 当DataReader关闭时,不关闭数据连接对象
            /// </summary>
            External
        }

        /// <summary>
        /// 为Command命令添加相关的信息
        /// </summary>
        /// <param name="command">原始的Command命令</param>
        /// <param name="conn">数据库连接</param>
        /// <param name="tran">事务</param>
        /// <param name="ct">Command命令的类型</param>
        /// <param name="txt">Command命令的文本</param>
        /// <param name="cps">Command命令的参数</param>
        internal static void PrepareCommand(IDbCommand command, IDbConnection conn, IDbTransaction tran, CommandType ct, string txt, IDataParameter[] cps)
        {
            command.Connection = conn;
            command.CommandText = txt;
            command.CommandType = ct;
            if (tran != null)
            {
                if (tran.Connection == null) throw new ArgumentException("事务已经回滚或提交.", "transaction");
                command.Transaction = tran;
            }
            if (cps != null && cps.Length > 0)
            {
                foreach (IDataParameter p in cps)
                {
                    if (p != null && (p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) && (p.Value == null))
                    {
                        p.Value = DBNull.Value;
                    }
                    command.Parameters.Add(p);
                }
            }
            if (conn.State != ConnectionState.Open)
            {
                try
                {
                    conn.Open();
                }
                catch (Exception ex)
                {
                    Log.Error("不能正常连接到数据库：" + conn.Database, false);
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 记录数据访问异常
        /// </summary>
        /// <param name="ex">异常</param>
        /// <param name="cmd">执行的数据库命令</param>
        internal string WriteDbException(Exception ex, IDbCommand cmd)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("错误描述：").AppendLine(ex.Message)
                .Append("数据库名：").AppendLine(cmd.Connection.Database)
                .Append("命令类型：").AppendLine(cmd.CommandType.ToString())
                .Append("命令文本：").AppendLine(cmd.CommandText);
            if (cmd.Parameters.Count > 0)
            {
                sb.AppendLine("命令参数：");
                int max = 0;
                foreach (IDataParameter p in cmd.Parameters)
                {
                    max = p.ParameterName.Length > max ? p.ParameterName.Length : max;
                }
                foreach (IDataParameter p in cmd.Parameters)
                {
                    sb.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), ToSqlValue(p.Value));
                }
            }
            string log = sb.ToString();
            Log.Error(log, false);
            return ex.Message;
        }

        /// <summary>
        /// 根据数据库连接对象的类型获取数据库类型
        /// </summary>
        /// <param name="connType">数据库连接对象类型</param>
        /// <returns>数据库类型</returns>
        internal static DbProvider GetDbProvider(Type connType)
        {
            if (connType.FullName.Contains("SqlConnection"))
            {
                return DbProvider.SqlServer;
            }
            if (connType.FullName.Contains("DB2Connection"))
            {
                return DbProvider.DB2;
            }
            if (connType.FullName.Contains("MySqlConnection"))
            {
                return DbProvider.MySql;
            }
            if (connType.FullName.Contains("FbConnection"))
            {
                return DbProvider.FireBird;
            }
            if (connType.FullName.Contains("IfxConnection"))
            {
                return DbProvider.Informix;
            }
            if (connType.FullName.Contains("AdsConnection"))
            {
                return DbProvider.Ads;
            }
            if (connType.FullName.Contains("NpgsqlConnection"))
            {
                return DbProvider.PostgreSQL;
            }
            if (connType.FullName.Contains("OdbcConnection"))
            {
                return DbProvider.Odbc;
            }
            if (connType.FullName.Contains("OleDbConnection"))
            {
                return DbProvider.OleDb;
            }
            if (connType.FullName.Contains("OracleConnection"))
            {
                return DbProvider.Oracle;
            }
            if (connType.FullName.Contains("SqlCeConnection"))
            {
                return DbProvider.SqlCe;
            }
            if (connType.FullName.Contains("SQLiteConnection") || connType.FullName.Contains("SqliteConnection"))
            {
                return DbProvider.Sqlite;
            }
            if (connType.FullName.Contains("AseConnection"))
            {
                return DbProvider.Sybase;
            }
            if (connType.FullName.Contains("VistaDBConnection"))
            {
                return DbProvider.VistaDB;
            }
            return DbProvider.Unknown;
        }

        /// <summary>
        /// 为SQL查询条件生成分页查询SQL语句
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <param name="provider">数据库类型</param>
        /// <param name="version">数据库版本</param>
        /// <param name="skip">使用这个命令返回的查询结果要跳过的行数</param>
        /// <returns>生成的SQL查询命令</returns>
        internal static string CreatePageSql(PS search, DbProvider provider, Version version, out int skip)
        {
            if (search.PageIndex >= search.PageCount)
            {
                search.PageIndex = search.PageCount - 1;
            }
            StringBuilder sbcmd = new StringBuilder();
            skip = 0;
            if (string.IsNullOrEmpty(search.TableName) || search.TableName.Trim().Length == 0)
            {
                sbcmd.Append("SELECT ");
                sbcmd.Append(search.FieldsName);
                goto RETURN;
            }
            if (search.PageSize == 0)
            {
                sbcmd.Append("SELECT ");
                sbcmd.Append(search.FieldsName);
                sbcmd.Append(" FROM ");
                sbcmd.Append(search.TableName);
                if (!string.IsNullOrEmpty(search.Where))
                {
                    sbcmd.Append(" WHERE ");
                    sbcmd.Append(search.Where);
                }
                if (search.OrderField.Count > 0)
                {
                    sbcmd.Append(search.OrderField);
                }
                goto RETURN;
            }
            switch (provider)
            {
                case DbProvider.PostgreSQL:
                case DbProvider.Sqlite:
                    {
                        #region Sqlite
                        // select .. from .. where .. order by .. limit .. offset 
                        sbcmd.Append("SELECT ");
                        sbcmd.Append(search.FieldsName);
                        sbcmd.Append(" FROM ");
                        sbcmd.Append(search.TableName);
                        if (!string.IsNullOrEmpty(search.Where))
                        {
                            sbcmd.Append(" WHERE ");
                            sbcmd.Append(search.Where);
                        }
                        if (search.OrderField.Count > 0)
                        {
                            sbcmd.Append(search.OrderField);
                        }
                        sbcmd.Append(" LIMIT ");
                        sbcmd.Append(search.PageSize);
                        sbcmd.Append(" OFFSET ");
                        sbcmd.Append(search.PageSize * search.PageIndex);
                        break;
                        #endregion
                    }
                case DbProvider.Oracle:
                    {
                        #region Oracle
                        if (search.PageIndex > 0)
                        {
                            sbcmd.Append("SELECT * FROM (");
                        }
                        sbcmd.Append("SELECT ROWNUM AS RN, AA.* FROM ( SELECT ");
                        sbcmd.Append(search.FieldsName);
                        sbcmd.Append(" FROM ");
                        sbcmd.Append(search.TableName);
                        if (!string.IsNullOrEmpty(search.Where))
                        {
                            sbcmd.Append(" WHERE ");
                            sbcmd.Append(search.Where);
                        }
                        if (search.OrderField.Count > 0)
                        {
                            sbcmd.Append(search.OrderField);
                        }
                        sbcmd.Append(" ) AA WHERE ROWNUM <= ");
                        sbcmd.Append((search.PageIndex + 1) * search.PageSize);
                        if (search.PageIndex > 0)
                        {
                            sbcmd.Append(" ) WHERE RN > ");
                            sbcmd.Append(search.PageSize * search.PageIndex);
                        }
                        break;
                        #endregion
                    }
                case DbProvider.MySql:
                    {
                        #region MySql
                        sbcmd.Append("SELECT ");
                        sbcmd.Append(search.FieldsName);
                        sbcmd.Append(" FROM ");
                        sbcmd.Append(search.TableName);
                        if (!string.IsNullOrEmpty(search.Where))
                        {
                            sbcmd.Append(" WHERE ");
                            sbcmd.Append(search.Where);
                        }
                        if (search.OrderField.Count > 0)
                        {
                            sbcmd.Append(search.OrderField);
                        }
                        sbcmd.Append(" LIMIT ");
                        sbcmd.Append(search.PageIndex * search.PageSize);
                        sbcmd.Append(",");
                        sbcmd.Append(search.PageSize);
                        break;
                        #endregion
                    }
                case DbProvider.SqlServer:
                    {
                        #region SqlServer
                        //版本小于2005或没有指定主键和排序字段
                        if ((version.Major < 9) || (search.OrderField.Count == 0 && string.IsNullOrEmpty(search.PrimaryKey)))
                        {
                            skip = search.PageSize * search.PageIndex;  //结果跳过指定行数
                            sbcmd.Append("SELECT TOP ");
                            sbcmd.Append((search.PageIndex + 1) * search.PageSize);
                            sbcmd.Append(" ");
                            sbcmd.Append(search.FieldsName);
                            sbcmd.Append(" FROM ");
                            sbcmd.Append(search.TableName);
                            if (!string.IsNullOrEmpty(search.Where))
                            {
                                sbcmd.Append(" WHERE ");
                                sbcmd.Append(search.Where);
                            }
                            if (search.OrderField.Count > 0)
                            {
                                sbcmd.Append(search.OrderField);
                            }
                        }
                        else
                        {
                            sbcmd.Append("SELECT TOP ");
                            sbcmd.Append(search.PageSize);
                            sbcmd.Append(" * FROM (SELECT ROW_NUMBER() OVER ( ");
                            if (search.OrderField.Count == 0)
                            {
                                sbcmd.Append("ORDER BY ");
                                sbcmd.Append(search.PrimaryKey);
                            }
                            else
                            {
                                sbcmd.Append(search.OrderField);
                            }
                            sbcmd.Append(") AS ROWID,");
                            sbcmd.Append(search.FieldsName);
                            sbcmd.Append(" FROM ");
                            sbcmd.Append(search.TableName);
                            if (!string.IsNullOrEmpty(search.Where))
                            {
                                sbcmd.Append(" WHERE ");
                                sbcmd.Append(search.Where);
                            }
                            sbcmd.Append(") AS AA WHERE ROWID > ");
                            sbcmd.Append(search.PageSize * search.PageIndex);
                        }
                        break;
                        #endregion
                    }
                case DbProvider.SqlCe:
                case DbProvider.OleDb:
                case DbProvider.VistaDB:
                    {
                        #region OleDb SqlCe VistaDB
                        skip = search.PageSize * search.PageIndex; //结果跳过指定行数
                        sbcmd.Append("SELECT TOP ");
                        sbcmd.Append((search.PageIndex + 1) * search.PageSize);
                        sbcmd.Append(" ");
                        sbcmd.Append(search.FieldsName);
                        sbcmd.Append(" FROM ");
                        sbcmd.Append(search.TableName);
                        if (!string.IsNullOrEmpty(search.Where))
                        {
                            sbcmd.Append(" WHERE ");
                            sbcmd.Append(search.Where);
                        }

                        if (search.OrderField.Count > 0)
                        {
                            sbcmd.Append(search.OrderField);
                        }
                        break;
                        #endregion
                    }
                case DbProvider.FireBird:
                    {
                        #region FireBird
                        /*FireBird支持两种分页方式:
                         * 2.0 以上: SELECT * FROM .. WHERE... ORDER BY ... ROWS 10 TO 20
                         * 1.x 版本: SELECT FIRST n SKIP m columns FROM ...  
                         */
                        sbcmd.Append("SELECT ");
                        #region For 1.0
                        if (version.Major < 2)
                        {
                            sbcmd.Append("FIRST ");
                            sbcmd.Append(search.PageSize);
                            sbcmd.Append(" ");
                            if (search.PageIndex > 0)
                            {
                                sbcmd.Append("SKIP ");
                                sbcmd.Append(search.PageIndex * search.PageSize);
                                sbcmd.Append(" ");
                            }
                        }
                        #endregion

                        sbcmd.Append(search.FieldsName);
                        sbcmd.Append(" FROM ");
                        sbcmd.Append(search.TableName);
                        if (!string.IsNullOrEmpty(search.Where))
                        {
                            sbcmd.Append(" WHERE ");
                            sbcmd.Append(search.Where);
                        }
                        if (search.OrderField.Count > 0)
                        {
                            sbcmd.Append(search.OrderField);
                        }
                        #region For 2.0
                        if (version.Major >= 2)
                        {
                            sbcmd.Append(" ROWS ");
                            sbcmd.Append(search.PageIndex * search.PageSize + 1);
                            sbcmd.Append(" TO ");
                            sbcmd.Append(search.PageSize * (search.PageIndex + 1));
                        }
                        #endregion
                        break;
                        #endregion
                    }
                case DbProvider.DB2:
                    {
                        #region DB2
                        //类似Sql Server
                        if (search.OrderField.Count == 0 && string.IsNullOrEmpty(search.PrimaryKey))
                        {
                            throw new Exception("主键或者排序字段必须有一个设置值");
                        }
                        sbcmd.Append("SELECT * FROM (SELECT ROWNUMBER() OVER ( ");

                        if (search.OrderField.Count == 0)
                        {
                            sbcmd.Append("ORDER BY ");
                            sbcmd.Append(search.PrimaryKey);
                        }
                        else
                        {
                            sbcmd.Append(search.OrderField);
                        }
                        sbcmd.Append(") AS ROWID,");
                        sbcmd.Append(search.FieldsName);
                        sbcmd.Append(" FROM ");
                        sbcmd.Append(search.TableName);
                        if (!string.IsNullOrEmpty(search.Where))
                        {
                            sbcmd.Append(" WHERE ");
                            sbcmd.Append(search.Where);
                        }
                        sbcmd.Append(") AS AA WHERE ROWID between ");
                        sbcmd.Append(search.PageSize * search.PageIndex + 1);
                        sbcmd.Append(" AND ");
                        sbcmd.Append((search.PageIndex + 1) * search.PageSize);
                        break;
                        #endregion
                    }
                case DbProvider.Informix:
                    {
                        #region Informix
                        //SELECT SKIP 2 FIRST 2  * FROM ... where ... ORDER BY ...
                        sbcmd.Append("SELECT SKIP ");
                        sbcmd.Append(search.PageIndex * search.PageSize);
                        sbcmd.Append("FIRST ");
                        sbcmd.Append(search.PageSize);
                        sbcmd.Append(" ");
                        sbcmd.Append(search.FieldsName);
                        sbcmd.Append(" FROM ");
                        sbcmd.Append(search.TableName);
                        if (!string.IsNullOrEmpty(search.Where))
                        {
                            sbcmd.Append(" WHERE ");
                            sbcmd.Append(search.Where);
                        }

                        sbcmd.Append(search.OrderField);
                        break;
                        #endregion
                    }
                case DbProvider.Ads:
                case DbProvider.Sybase:
                    {
                        #region
                        // SELECT TOP 2 START AT 5 * FROM ... ORDER BY ....
                        if (search.OrderField.Count == 0 && string.IsNullOrEmpty(search.PrimaryKey))
                        {
                            throw new Exception("主键或者排序字段必须有一个设置值");
                        }
                        sbcmd.Append("SELECT TOP ");
                        sbcmd.Append(search.PageSize);
                        if (search.PageIndex > 0)
                        {
                            sbcmd.Append(" START ");
                            sbcmd.Append(search.PageIndex * search.PageSize);
                        }
                        sbcmd.Append(" ");
                        sbcmd.Append(search.FieldsName);
                        sbcmd.Append(" FROM ");
                        sbcmd.Append(search.TableName);
                        if (!string.IsNullOrEmpty(search.Where))
                        {
                            sbcmd.Append(" WHERE ");
                            sbcmd.Append(search.Where);
                        }
                        if (search.OrderField.Count > 0)
                        {
                            sbcmd.Append(search.OrderField);
                        }
                        break;
                        #endregion
                    }
                default:
                    {
                        throw new NotImplementedException();
                    }
            }
        RETURN:
            return sbcmd.ToString();
        }

        /// <summary>
        /// 根据查询条件返回这个查询总共有多少条记录的语句
        /// </summary>
        /// <param name="search">查询条件</param>
        /// <returns>COUNT(*)语句</returns>
        internal static string CreateCountSql(PS search)
        {
            StringBuilder sbcmd = new StringBuilder();
            if (string.IsNullOrEmpty(search.TableName) || search.TableName.Trim().Length == 0)
            {
                sbcmd.Append("SELECT 1");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(search.PrimaryKey))
                {
                    sbcmd.Append("SELECT COUNT(*) FROM ");
                }
                else
                {
                    sbcmd.AppendFormat("SELECT COUNT({0}) FROM ", search.PrimaryKey);
                }
                sbcmd.Append(search.TableName);
                if (!string.IsNullOrEmpty(search.Where))
                {
                    sbcmd.Append(" WHERE ");
                    sbcmd.Append(search.Where);
                }
            }
            return sbcmd.ToString();
        }

        public virtual CMD CreateCommand()
        {
            return new CMD();
        }

        public virtual CMD CreateCommand(string commandText)
        {
            return new CMD() { CommandText = commandText, CommandType = commandText.Contains(" ") ? CommandType.Text : CommandType.StoredProcedure };
        }

        public virtual CMD CreateCommand(string commandText, CommandType type)
        {
            return new CMD() { CommandText = commandText, CommandType = type };
        }

        public virtual CMD CreateCommand(string commandText, CommandType type, P[] parameters)
        {
            CMD cmd = new CMD() { CommandText = commandText, CommandType = type };
            if (parameters != null && parameters.Length > 0)
            {
                cmd.AddRange(parameters);
            }
            return cmd;
        }

        public virtual PS CreatePageCommand()
        {
            return new PS();
        }

        public virtual PS CreatePageCommand(int pageIndex, int pageSize)
        {
            return new PS() { PageSize = pageSize, PageIndex = pageIndex };
        }
        #endregion
    }
    #endregion

    /// <summary>
    /// 数据库类型
    /// </summary>
    public enum DbProvider
    {
        /// <summary>
        /// 未知数据库类型
        /// </summary>
        Unknown = 0,

        /// <summary>
        /// ODBC数据源
        /// </summary>
        Odbc = 1,

        /// <summary>
        /// OLEDB数据源
        /// </summary>
        OleDb = 2,

        /// <summary>
        /// SQLSERVER数据库
        /// </summary>
        SqlServer = 3,

        /// <summary>
        /// Oracle数据库
        /// </summary>
        Oracle = 4,

        /// <summary>
        /// Advantage数据库
        /// </summary>
        Ads = 5,

        /// <summary>
        /// MySql数据库
        /// </summary>
        MySql = 6,

        /// <summary>
        /// Postgre数据库
        /// </summary>
        PostgreSQL = 7,

        /// <summary>
        /// SQLite数据库
        /// </summary>
        Sqlite = 8,

        /// <summary>
        /// Firebird数据库
        /// </summary>
        FireBird = 9,

        /// <summary>
        /// IBM DB2数据库
        /// </summary>
        DB2 = 10,

        /// <summary>
        /// Infomix数据库
        /// </summary>
        Informix = 11,

        /// <summary>
        /// Sybase数据库
        /// </summary>
        Sybase = 12,

        /// <summary>
        /// SQL嵌入式数据库
        /// </summary>
        SqlCe = 13,

        /// <summary>
        /// VistaDB数据库
        /// </summary>
        VistaDB = 14
    }

    public class DataBaseException : Exception
    {
        public DataBaseException()
        {
        }

        public DataBaseException(string errmsg)
            : base(errmsg)
        {
            this.ErrNo = 0;
            this.ErrLine = 0;
        }
        public DataBaseException(int errno, int errline, string errmsg)
            : base(errmsg)
        {
            this.ErrNo = errno;
            this.ErrLine = errline;
        }
        public int ErrLine
        {
            get;
            set;
        }
        public int ErrNo
        {
            get;
            set;
        }
        public override string ToString()
        {
            return string.Format("错误代码【{0}】，错误行号【{1}】，错误内容【{2}】", ErrNo, ErrLine, Message);
        }
    }

    #region DbResult

    /// <summary>
    /// 数据库命令的参数集合
    /// </summary>
    public class DataParameterCollection : IDisposable, IEnumerable
    {
        private string ParameterPrefix;

        /// <summary>
        /// 内部构造器
        /// </summary>
        /// <param name="parms"></param>
        internal DataParameterCollection(IDataParameterCollection parms, string prefix)
        {
            this.parameters = parms;
            this.ParameterPrefix = prefix;
        }
        private IDataParameterCollection parameters = null;

        /// <summary>
        /// 获取指定位置处的数据库命令参数
        /// </summary>
        /// <param name="index">指定位置</param>
        /// <returns>数据库命令参数</returns>
        public IDbDataParameter this[int index]
        {
            get
            {
                if (parameters != null)
                {
                    return (IDbDataParameter)this.parameters[index];
                }
                return null;
            }
        }

        /// <summary>
        /// 获取指定名称的数据库命令参数
        /// </summary>
        /// <param name="index">定名称</param>
        /// <returns>数据库命令参数</returns>
        public IDbDataParameter this[string name]
        {
            get
            {
                if (parameters != null)
                {
                    if (!string.IsNullOrWhiteSpace(this.ParameterPrefix) && !name.StartsWith(this.ParameterPrefix))
                    {
                        name = this.ParameterPrefix + name;
                    }
                    return (IDbDataParameter)this.parameters[name];
                }
                return null;
            }
        }

        /// <summary>
        /// 检查是否包含某个指定名称的参数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool Contains(string name)
        {
            if (parameters != null)
            {
                if (!string.IsNullOrWhiteSpace(this.ParameterPrefix) && !name.StartsWith(this.ParameterPrefix))
                {
                    name = this.ParameterPrefix + name;
                }
                return parameters.Contains(name);
            }
            return false;
        }

        /// <summary>
        /// 清空参数列表
        /// </summary>
        public void Clear()
        {
            if (parameters != null)
            {
                parameters.Clear();
            }
        }

        /// <summary>
        /// 返回参数的个数
        /// </summary>
        public int Count
        {
            get
            {
                return parameters != null ? parameters.Count : 0;
            }
        }

        #region IDisposable 成员
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (this.parameters != null)
            {
                this.parameters.Clear();
                this.parameters = null;
            }
        }

        #endregion

        #region IEnumerable 成员

        /// <summary>
        /// 获取枚举的访问器
        /// </summary>
        /// <returns></returns>
        public IEnumerator GetEnumerator()
        {
            if (parameters != null)
            {
                return parameters.GetEnumerator();
            }
            return null;
        }

        #endregion
    }

    /// <summary>
    /// 数据库命令执行产生的结果
    /// </summary>
    public class ResultBase : IDisposable
    {
        internal static LogAdapter Log = LogAdapter.GetLogger("Db");
        internal string commandText = null;
        /// <summary>
        /// 数据库命令
        /// </summary>
        public string CommandText
        {
            get
            {
                return commandText;
            }
        }

        internal CommandType commandType;
        /// <summary>
        /// 数据库命令的类型
        /// </summary>
        public CommandType CommandType
        {
            get
            {
                return commandType;
            }
        }

        internal DataParameterCollection parameters = null;

        /// <summary>
        /// 获取数据库命令的参数
        /// </summary>
        public DataParameterCollection Parameters
        {
            get
            {
                return this.parameters;
            }
        }

        /// <summary>
        /// 根据Command命令生成一个结果
        /// <para>
        /// 如果数据库命令的参数中有输出参数,则会记录所有的参数信息,否则不会记录参数
        /// </para>
        /// </summary>
        /// <param name="command">Command命令</param>
        internal ResultBase(IDbCommand command, IDataAccess db)
        {
            if (command != null)
            {
                this.commandText = command.CommandText;
                this.commandType = command.CommandType;
                this.parameters = new DataParameterCollection(command.Parameters, db.ParameterPrefix);
                command.Dispose();
            }
        }

        /// <summary>
        /// 根据Command命令生成一个结果
        /// <para>
        /// 如果数据库命令的参数中有输出参数,则会记录所有的参数信息,否则不会记录参数
        /// </para>
        /// </summary>
        /// <param name="commandText">命令文本</param>
        /// <param name="commandType">命令类型</param>
        /// <param name="parameters">命令参数</param>
        internal ResultBase(string commandText, CommandType commandType, IDataParameterCollection parameters, IDataAccess db)
        {
            this.commandText = commandText;
            this.commandType = commandType;
            this.parameters = new DataParameterCollection(parameters, db.ParameterPrefix);
        }

        /// <summary>
        /// 根据Command命令生成一个结果
        /// <para>
        /// 如果数据库命令的参数中有输出参数,则会记录所有的参数信息,否则不会记录参数
        /// </para>
        /// </summary>
        /// <param name="commandText">命令文本</param>
        /// <param name="commandType">命令类型</param>
        /// <param name="parameters">命令参数</param>
        internal ResultBase(string commandText, CommandType commandType, DataParameterCollection parameters)
        {
            this.commandText = commandText;
            this.commandType = commandType;
            this.parameters = parameters;
        }

        #region IDisposable Members
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            this.commandText = null;
            if (this.parameters != null)
            {
                this.parameters.Dispose();
            }
        }

        #endregion
    }

    #region NonQueryResult
    /// <summary>
    /// 执行Command对象的ExecuteNonQuery()方法产生的结果
    /// </summary>
    public class NonQueryResult : ResultBase, IDisposable
    {
        private StringBuilder sbdesc = null;
        private int value = 0;
        /// <summary>
        /// 数据库命令执行后的返回值
        /// </summary>
        public int Value
        {
            get
            {
                return this.value;
            }
        }

        /// <summary>
        /// 使用一个数据库命令的执行后的返回值和数据库命令初始化对象
        /// </summary>
        /// <param name="result">结果</param>
        /// <param name="command">命令</param>
        internal NonQueryResult(int result, IDbCommand command, IDataAccess db)
            : base(command, db)
        {
            this.value = result;
            Log.Debug(this.Description, false);
        }

        /// <summary>
        /// 结果描述
        /// </summary>
        public string Description
        {
            get
            {
                if (sbdesc == null)
                {
                    sbdesc = new System.Text.StringBuilder();

                    sbdesc.AppendLine("数据库返回结果信息如下");
                    sbdesc.AppendLine("命令类型:" + CommandType);
                    sbdesc.AppendLine("命令文本:" + CommandText);
                    if (Parameters != null && Parameters.Count > 0)
                    {
                        sbdesc.AppendLine("参数列表:");
                        int max = 0;
                        foreach (IDataParameter p in Parameters)
                        {
                            max = p.ParameterName.Length > max ? p.ParameterName.Length : max;
                        }
                        foreach (IDataParameter p in Parameters)
                        {
                            if (p.DbType == DbType.DateTime)
                            {
                                sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), ((DateTime)p.Value).ToString("yyyy-MM-dd HH:mm:ss.fff"));
                            }
                            else
                            {
                                sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), p.Value);
                            }
                        }
                    }
                    sbdesc.AppendLine("影响行数:" + value);
                }
                return sbdesc.ToString();
            }
        }

        #region IDisposable Members

        /// <summary>
        /// 释放资源
        /// </summary>
        void IDisposable.Dispose()
        {
            base.Dispose();
        }

        #endregion
    }
    #endregion

    #region ScalerResult
    /// <summary>
    /// 执行Command对象的ExecuteScaler()方法产生的结果
    /// </summary>
    public class ScalerResult : ResultBase, IDisposable
    {
        private StringBuilder sbdesc = null;
        private object value;
        /// <summary>
        /// 数据库命令执行后的返回值
        /// </summary>
        public object Value
        {
            get
            {
                return this.value;
            }
        }

        /// <summary>
        /// 使用一个数据库命令的执行后的返回值和数据库命令初始化对象
        /// </summary>
        /// <param name="result">结果</param>
        /// <param name="command">命令</param>
        /// <param name="debug">是否记录调试日志</param>
        internal ScalerResult(object result, IDbCommand command, IDataAccess db)
            : base(command, db)
        {
            this.value = result;
            Log.Debug(this.Description, false);
        }

        /// <summary>
        /// 检测返回的值是否为null或者DBNull.Value(如果数据库没有返回行数据,则为null,如果数据库返回了行数据,但为NULL,则为DBNull.Value
        /// </summary>
        public bool IsNullOrDbNull
        {
            get
            {
                return value == null || Convert.IsDBNull(value);
            }
        }

        /// <summary>
        /// 如果数据库没有返回行数据,则返回true,否则返回false
        /// </summary>
        public bool IsNull
        {
            get
            {
                return value == null;
            }
        }

        /// <summary>
        /// 如果数据返回了数据,但第一行第一列为NULL,则返回true,否则返回false
        /// </summary>
        public bool IsDBNull
        {
            get
            {
                return Convert.IsDBNull(value);
            }
        }

        /// <summary>
        /// 返回Int32类型的值
        /// </summary>
        public int IntValue
        {
            get
            {
                if (IsNullOrDbNull)
                {
                    throw new Exception("从数据库返回了NULL或DBNULL数据");
                }
                return Convert.ToInt32(this.value);
            }
        }

        /// <summary>
        /// 返回Int64类型的值
        /// </summary>
        public long LongValue
        {
            get
            {
                if (IsNullOrDbNull)
                {
                    throw new Exception("从数据库返回了NULL或DBNULL数据");
                }
                return Convert.ToInt64(this.value);
            }
        }

        /// <summary>
        /// 返回浮点类型的值
        /// </summary>
        public float FloatValue
        {
            get
            {
                if (IsNullOrDbNull)
                {
                    throw new Exception("从数据库返回了NULL或DBNULL数据");
                }
                return Convert.ToFloat(this.value);
            }
        }

        /// <summary>
        /// 返回双精度类型的值
        /// </summary>
        public double DoubleValue
        {
            get
            {
                if (IsNullOrDbNull)
                {
                    throw new Exception("从数据库返回了NULL或DBNULL数据");
                }
                return Convert.ToDouble(this.value);
            }
        }

        /// <summary>
        /// 返回布尔类型的值(只检查是否为true,t,1)
        /// </summary>
        public bool BoolValue
        {
            get
            {
                if (IsNullOrDbNull)
                {
                    throw new Exception("从数据库返回了NULL或DBNULL数据");
                }
                string val = this.StringValue.ToLower();
                return PTA.Convert.ToBoolean(val);
            }
        }

        /// <summary>
        /// 返回时间类型的值
        /// </summary>
        public DateTime DateTimeValue
        {
            get
            {
                if (IsNullOrDbNull)
                {
                    throw new Exception("从数据库返回了NULL或DBNULL数据");
                }
                return Convert.ToDateTime(this.value);
            }
        }

        /// <summary>
        /// 返回String类型的值
        /// </summary>
        public string StringValue
        {
            get
            {
                if (IsNullOrDbNull)
                {
                    return string.Empty;
                }
                return Convert.ToString(this.value);
            }
        }

        /// <summary>
        /// 结果描述
        /// </summary>
        public string Description
        {
            get
            {
                if (sbdesc == null)
                {
                    sbdesc = new System.Text.StringBuilder();

                    sbdesc.AppendLine("数据库返回结果信息如下");
                    sbdesc.AppendLine("命令类型:" + CommandType);
                    sbdesc.AppendLine("命令文本:" + CommandText);
                    if (Parameters != null && Parameters.Count > 0)
                    {
                        sbdesc.AppendLine("参数列表:");
                        int max = 0;
                        foreach (IDataParameter p in Parameters)
                        {
                            max = p.ParameterName.Length > max ? p.ParameterName.Length : max;
                        }
                        foreach (IDataParameter p in Parameters)
                        {
                            sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), p.Value);
                        }
                    }
                    sbdesc.AppendLine("查询结果:" + value);
                }
                return sbdesc.ToString();
            }
        }

        /// <summary>
        /// 转换为字符串
        /// </summary>
        /// <returns>结果转换后的字符串</returns>
        public override string ToString()
        {
            return this.value.ToString();
        }

        #region IDisposable Members

        /// <summary>
        /// 释放资源
        /// </summary>
        void IDisposable.Dispose()
        {
            this.value = null;
            base.Dispose();
        }

        #endregion
    }
    #endregion

    #region DataTableResult
    /// <summary>
    /// 执行CommandAdapter对象填充的表结果
    /// </summary>
    public class DataTableResult : ResultBase, IListSource, IDisposable
    {
        private StringBuilder sbdesc = null;
        private DataTable value;
        /// <summary>
        /// 数据库命令执行后的返回值
        /// </summary>
        public DataTable Value
        {
            get
            {
                return this.value;
            }
        }

        /// <summary>
        /// 使用一个数据库命令的执行后的返回值和数据库命令初始化对象
        /// </summary>
        /// <param name="result">结果</param>
        /// <param name="command">命令</param>
        /// <param name="debug">是否记录调试日志</param>
        internal DataTableResult(DataTable result, IDbCommand command, IDataAccess db)
            : base(command, db)
        {
            this.value = result;
            if (value.Columns.Count == 3 && value.Columns["ERRNO"] != null && value.Columns["ERRMSG"] != null && value.Columns["ERRLINE"] != null && value.Rows.Count > 0)
            {
                throw new DataBaseException(PTA.Convert.ToInt32(value.Rows[1]["ERRNO"]), PTA.Convert.ToInt32(value.Rows[1]["ERRLINE"]), PTA.Convert.ToString(value.Rows[1]["ERRMSG"]));
            }
            Log.Debug(this.Description, false);
        }

        internal DataTableResult(DataTable result, string commandText, CommandType commandType, IDataParameterCollection parameters, IDataAccess db)
            : base(commandText, commandType, parameters, db)
        {
            this.value = result;
        }

        internal DataTableResult(DataTable result, string commandText, CommandType commandType, DataParameterCollection parameters)
            : base(commandText, commandType, parameters)
        {
            this.value = result;
        }

        public List<T> ReadEntityArray<T>()
             where T : BaseEntity, new()
        {
            List<T> result = new List<T>();
            foreach (DataRow dr in this.value.Rows)
            {
                T item = new T();
                EntityHelper.SetObjectProperty(item, dr);
                result.Add(item);
            }
            return result;
        }

        /// <summary>
        /// 结果描述
        /// </summary>
        public string Description
        {
            get
            {
                if (sbdesc == null)
                {
                    sbdesc = new System.Text.StringBuilder();

                    sbdesc.AppendLine("数据库返回结果信息如下");
                    sbdesc.AppendLine("命令类型:" + CommandType);
                    sbdesc.AppendLine("命令文本:" + CommandText);
                    int max = 0;
                    if (Parameters != null && Parameters.Count > 0)
                    {
                        sbdesc.AppendLine("参数列表:");
                        foreach (IDataParameter p in Parameters)
                        {
                            max = p.ParameterName.Length > max ? p.ParameterName.Length : max;
                        }
                        foreach (IDataParameter p in Parameters)
                        {
                            if (p.DbType == DbType.DateTime)
                            {
                                sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), ((DateTime)p.Value).ToString("yyyy-MM-dd HH:mm:ss.fff"));
                            }
                            else
                            {
                                sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), p.Value);
                            }
                        }
                    }
                    max = 0;
                    sbdesc.AppendLine("结果行数:" + value.Rows.Count.ToString());
                    sbdesc.AppendLine("各列类型:");
                    foreach (DataColumn dc in value.Columns)
                    {
                        max = dc.ColumnName.Length > max ? dc.ColumnName.Length : max;
                    }
                    foreach (DataColumn dc in value.Columns)
                    {
                        sbdesc.AppendFormatLine("{0} : {1}", dc.ColumnName.PadRight(max, ' '), dc.DataType.ToString().PadRight(11, ' '));
                    }
                }
                return sbdesc.ToString();
            }
        }

        #region IDisposable Members

        /// <summary>
        /// 释放资源
        /// </summary>
        void IDisposable.Dispose()
        {
            this.value.Dispose();
            base.Dispose();
        }

        #endregion

        #region IListSource Members

        /// <summary>
        /// 集合是 IList 对象集合
        /// </summary>
        public bool ContainsListCollection
        {
            get { return (this.value as IListSource).ContainsListCollection; }
        }

        /// <summary>
        /// 返回一个数据绑定控件可用的数据源
        /// </summary>
        /// <returns>数据源</returns>
        public IList GetList()
        {
            return (this.value as IListSource).GetList();
        }

        #endregion
    }
    #endregion

    #region DataSetResult
    /// <summary>
    /// 执行CommandAdapter对象填充的数据集结果
    /// </summary>
    public class DataSetResult : ResultBase, IListSource, IDisposable
    {
        private StringBuilder sbdesc = null;
        private DataSet value;
        /// <summary>
        /// 数据库命令执行后的返回值
        /// </summary>
        public DataSet Value
        {
            get
            {
                return this.value;
            }
        }

        /// <summary>
        /// 使用一个数据库命令的执行后的返回值和数据库命令初始化对象
        /// </summary>
        /// <param name="result">结果</param>
        /// <param name="command">命令</param>
        /// <param name="debug">是否记录调试日志</param>
        internal DataSetResult(DataSet result, IDbCommand command, IDataAccess db)
            : base(command, db)
        {
            this.value = result;
            foreach (DataTable t in value.Tables)
            {
                if (t.Columns.Count == 3 && t.Columns["ERRNO"] != null && t.Columns["ERRMSG"] != null && t.Columns["ERRLINE"] != null && t.Rows.Count > 0)
                {
                    throw new DataBaseException(PTA.Convert.ToInt32(t.Rows[1]["ERRNO"]), PTA.Convert.ToInt32(t.Rows[1]["ERRLINE"]), PTA.Convert.ToString(t.Rows[1]["ERRMSG"]));
                }
            }
            Log.Debug(this.Description, false);
        }

        /// <summary>
        /// 结果描述
        /// </summary>
        public string Description
        {
            get
            {
                if (sbdesc == null)
                {
                    sbdesc = new System.Text.StringBuilder();

                    sbdesc.AppendLine("数据库返回结果信息如下");
                    sbdesc.AppendLine("命令类型:" + CommandType);
                    sbdesc.AppendLine("命令文本:" + CommandText);
                    int max = 0;
                    if (Parameters != null && Parameters.Count > 0)
                    {
                        sbdesc.AppendLine("参数列表:");
                        foreach (IDataParameter p in Parameters)
                        {
                            max = p.ParameterName.Length > max ? p.ParameterName.Length : max;
                        }
                        foreach (IDataParameter p in Parameters)
                        {
                            if (p.DbType == DbType.DateTime)
                            {
                                sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), ((DateTime)p.Value).ToString("yyyy-MM-dd HH:mm:ss.fff"));
                            }
                            else
                            {
                                sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), p.Value);
                            }
                        }
                    }
                    foreach (DataTable dt in value.Tables)
                    {
                        max = 0;
                        sbdesc.AppendLine("表名    :" + dt.TableName);
                        sbdesc.AppendLine("结果行数:" + dt.Rows.Count);
                        sbdesc.AppendLine("各列类型:");
                        foreach (DataColumn dc in dt.Columns)
                        {
                            max = dc.ColumnName.Length > max ? dc.ColumnName.Length : max;
                        }
                        foreach (DataColumn dc in dt.Columns)
                        {
                            sbdesc.AppendFormatLine("{0} : {1}", dc.ColumnName.PadRight(max, ' '), dc.DataType.ToString().PadRight(11, ' '));
                        }
                    }
                }
                return sbdesc.ToString();
            }
        }

        #region IDisposable Members

        /// <summary>
        /// 释放资源
        /// </summary>
        void IDisposable.Dispose()
        {
            this.sbdesc.Remove(0, this.sbdesc.Length);
            this.value.Dispose();
            base.Dispose();
        }
        #endregion

        #region IListSource Members

        /// <summary>
        /// 集合是 IList 对象集合(true)
        /// </summary>
        public bool ContainsListCollection
        {
            get { return (this.value as IListSource).ContainsListCollection; }
        }

        /// <summary>
        /// 返回一个数据绑定控件可用的数据源
        /// </summary>
        /// <returns>数据源</returns>
        public IList GetList()
        {
            return (this.value as IListSource).GetList();
        }

        #endregion
    }
    #endregion

    #region DataReader
    /// <summary>
    /// 包装的数据读取器
    /// </summary>
    public class DataReader : ResultBase, IDataReader, IEnumerable, IDisposable
    {
        private IDataReader dr;
        private DbDataReader dbdr = null;
        private int rowidx = -1;
        private Dictionary<string, int> fieles = null;
        /// <summary>
        /// 根据数据读取器和相对应的Command生成一个包装后的数据读取器对象
        /// </summary>
        /// <param name="dr">原始数据读取器</param>
        /// <param name="command">数据命令相关信息</param>
        /// <param name="debug">是否记录调试日志</param>
        internal DataReader(IDataReader dr, IDbCommand command, IDataAccess db)
            : base(command, db)
        {
            this.dr = dr;
            this.dbdr = dr as DbDataReader;
            fieles = new Dictionary<string, int>();
            for (int i = 0; i < dr.FieldCount; i++)
            {
                var name = dr.GetName(i).ToUpper();
                if (!fieles.ContainsKey(name))
                {
                    fieles.Add(name, i);
                }
            }
            if (dr.FieldCount == 3 && this.HasField("ERRNO", "ERRMSG", "ERRLINE") && dr.Read())
            {
                throw new DataBaseException(dr.GetInt32(dr.GetOrdinal("ERRNO")), dr.GetInt32(dr.GetOrdinal("ERRLINE")), dr.GetString(dr.GetOrdinal("ERRMSG")));
            }
            Log.Debug(this.Description, false);
        }

        /// <summary>
        /// 检查是否包含所有参数指定的字段
        /// </summary>
        /// <param name="field">字段</param>
        /// <param name="fields">其它字段</param>
        /// <returns></returns>
        public bool HasField(string field, params string[] fields)
        {
            return this.fieles.ContainsKey(field.ToUpper()) && fields.Any(x => this.fieles.ContainsKey(x.ToUpper()));
        }

        /// <summary>
        /// 指示数据读取器的游标向前移动指定长度
        /// </summary>
        /// <param name="skip">游标移动长度</param>
        public void Skip(long skip)
        {
            for (; skip > 0 && dr.Read(); rowidx++, skip--) ;
        }

        /// <summary>
        /// 原始的DataReader对象
        /// </summary>
        public IDataReader OriDataReader
        {
            get
            {
                return this.dr;
            }
        }

        /// <summary>
        /// 返回指定列的名称
        /// </summary>
        /// <param name="index">列的序号</param>
        /// <returns>指定列的名称</returns>
        public string GetName(int index)
        {
            return this.dr.GetName(index);
        }

        /// <summary>
        /// 返回指定列的序号
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>列的序号</returns>
        public int GetOrdinal(string name)
        {
            try
            {
                return this.fieles[name.ToUpper()];
            }
            catch
            {
                throw new Exception(string.Format("未找到数据读取器字段:{1}{0}{2}", Environment.NewLine, name, Description));
            }
        }

        /// <summary>
        /// 检查数据读取器的某个字段是否为DBNull
        /// </summary>
        /// <param name="name"></param>
        private void CheckFieldNotNull(string name)
        {
            if (IsDBNull(name))
            {
                throw new Exception(string.Format("要获取的列{1}的为DBNull{0}{2}", Environment.NewLine, name, Description));
            }
        }

        /// <summary>
        /// 检查数据读取器的某个字段是否为DBNull
        /// </summary>
        /// <param name="ordinal">列索引</param>
        private void CheckFieldNotNull(int ordinal)
        {
            if (dr.IsDBNull(ordinal))
            {
                throw new Exception(string.Format("要获取的列{1}的为DBNull{0}{2}", Environment.NewLine, ordinal, Description));
            }
        }

        /// <summary>
        /// 执行记取命令
        /// </summary>
        /// <returns>返回一人值,指示DataReader是否成功读取了一条数据</returns>
        public bool Read()
        {
            if (this.dr.Read())
            {
                rowidx++;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 行索引值(默认为-1,当读取了第一行行,变为0)
        /// </summary>
        public int CurrentRowIndex
        {
            get
            {
                return this.rowidx;
            }
        }

        #region GetBoolean

        /// <summary>
        /// 返回bool
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public bool GetBoolean(string name)
        {
            CheckFieldNotNull(name);
            return PTA.Convert.ToBoolean(this.dr[name].ToString());
        }

        /// <summary>
        /// 返回bool
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public bool GetBoolean(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return PTA.Convert.ToBoolean(this.dr[ordinal].ToString());
        }

        /// <summary>
        /// 返回bool
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public bool GetBoolean(string name, bool defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetBoolean(name);
        }

        /// <summary>
        /// 返回bool
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public bool GetBoolean(int ordinal, bool defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetBoolean(ordinal);
        }

        /// <summary>
        /// 返回指定列的Boolean值,如果指定列为DBNull,则返回null
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public bool? GetBooleanNull(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            string o = this.dr[name].ToString().Trim();
            return o == "1" || o.Equals("T", StringComparison.OrdinalIgnoreCase) || o.Equals("True", StringComparison.OrdinalIgnoreCase) || o.Equals("Y", StringComparison.OrdinalIgnoreCase);
        }

        /// <summary>
        /// 返回指定列的Boolean值,如果指定列为DBNull,则返回null
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public bool? GetBooleanNull(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            string o = this.dr[ordinal].ToString().Trim();
            return o == "1" || o.Equals("T", StringComparison.OrdinalIgnoreCase) || o.Equals("True", StringComparison.OrdinalIgnoreCase) || o.Equals("Y", StringComparison.OrdinalIgnoreCase);
        }
        #endregion

        #region GetByte

        /// <summary>
        /// 返回byte
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public byte GetByte(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetByte(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回byte
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public byte GetByte(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetByte(ordinal);
        }

        /// <summary>
        /// 返回byte
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public byte GetByte(string name, byte defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetByte(name);
        }

        /// <summary>
        /// 返回byte
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public byte GetByte(int ordinal, byte defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetByte(ordinal);
        }

        /// <summary>
        /// 返回byte
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public byte? GetByteNull(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetByte(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回byte
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public byte? GetByteNull(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetByte(ordinal);
        }

        /// <summary>
        /// 读取字节
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="fieldoffset">偏移量</param>
        /// <param name="buffer">缓冲区</param>
        /// <param name="bufferoffset">缓冲区偏移量</param>
        /// <param name="length">长度</param>
        /// <returns>实际读取的内容的长度</returns>
        public long GetBytes(string name, long fieldoffset, byte[] buffer, int bufferoffset, int length)
        {
            CheckFieldNotNull(name);
            return this.dr.GetBytes(this.GetOrdinal(name), fieldoffset, buffer, bufferoffset, length);
        }

        /// <summary>
        /// 读取字节
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="fieldoffset">偏移量</param>
        /// <param name="buffer">缓冲区</param>
        /// <param name="bufferoffset">缓冲区偏移量</param>
        /// <param name="length">长度</param>
        /// <returns>实际读取的内容的长度</returns>
        public long GetBytes(int ordinal, long fieldoffset, byte[] buffer, int bufferoffset, int length)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetBytes(ordinal, fieldoffset, buffer, bufferoffset, length);
        }


        #endregion

        #region GetChars

        /// <summary>
        /// 返回Char
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public char GetChar(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetChar(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回Char
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public char GetChar(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetChar(ordinal);
        }

        /// <summary>
        /// 返回Char
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public char GetChar(string name, char defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetChar(name);
        }

        /// <summary>
        /// 返回Char
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public char GetChar(int ordinal, char defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetChar(ordinal);
        }

        /// <summary>
        /// 返回Char
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public char? GetCharNull(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetChar(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回Char
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public char? GetCharNull(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetChar(ordinal);
        }

        /// <summary>
        /// 读取字符串
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="fieldoffset">偏移量</param>
        /// <param name="buffer">目标</param>
        /// <param name="bufferoffset">目标偏移量</param>
        /// <param name="length">长度</param>
        /// <returns>读取的字节长度</returns>
        public long GetChars(string name, long fieldoffset, char[] buffer, int bufferoffset, int length)
        {
            CheckFieldNotNull(name);
            return this.dr.GetChars(this.GetOrdinal(name), fieldoffset, buffer, bufferoffset, length);
        }

        /// <summary>
        /// 读取字符串
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="fieldoffset">偏移量</param>
        /// <param name="buffer">目标</param>
        /// <param name="bufferoffset">目标偏移量</param>
        /// <param name="length">长度</param>
        /// <returns>读取的字节长度</returns>
        public long GetChars(int ordinal, long fieldoffset, char[] buffer, int bufferoffset, int length)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetChars(ordinal, fieldoffset, buffer, bufferoffset, length);
        }

        #endregion

        #region GetInt16

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public short GetInt16(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetInt16(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public short GetInt16(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetInt16(ordinal);
        }

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="convert">是否使用Convert.ToInt16来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public short GetInt16(string name, bool convert)
        {
            CheckFieldNotNull(name);
            if (convert)
            {
                return Convert.ToInt16(this[this.GetOrdinal(name)]);
            }
            else
            {
                return GetInt16(name);
            }
        }

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="convert">是否使用Convert.ToInt16来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public short GetInt16(int ordinal, bool convert)
        {
            CheckFieldNotNull(ordinal);
            if (convert)
            {
                return Convert.ToInt16(this[ordinal]);
            }
            else
            {
                return GetInt16(ordinal);
            }
        }

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public short GetInt16(string name, short defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetInt16(name);
        }

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public short GetInt16(int ordinal, short defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetInt16(ordinal);
        }

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToInt16来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public short GetInt16(string name, short defaultValue, bool convert)
        {
            return this.IsDBNull(name) ? defaultValue : GetInt16(name, convert);
        }

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToInt16来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public short GetInt16(int ordinal, short defaultValue, bool convert)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetInt16(ordinal, convert);
        }

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public short? GetInt16Null(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetInt16(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回Int16
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public short? GetInt16Null(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetInt16(ordinal);
        }
        #endregion

        #region GetInt32

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public int GetInt32(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetInt32(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public int GetInt32(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetInt32(ordinal);
        }

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="convert">是否使用Convert.ToInt32来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public int GetInt32(string name, bool convert)
        {
            CheckFieldNotNull(name);
            if (convert)
            {
                return Convert.ToInt32(this[this.GetOrdinal(name)]);
            }
            else
            {
                return GetInt32(name);
            }
        }

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="convert">是否使用Convert.ToInt32来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public int GetInt32(int ordinal, bool convert)
        {
            CheckFieldNotNull(ordinal);
            if (convert)
            {
                return Convert.ToInt32(this[ordinal]);
            }
            else
            {
                return GetInt32(ordinal);
            }
        }

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public int GetInt32(string name, int defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetInt32(name);
        }

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public int GetInt32(int ordinal, int defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetInt32(ordinal);
        }

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToInt32来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public int GetInt32(string name, int defaultValue, bool convert)
        {
            return this.IsDBNull(name) ? defaultValue : GetInt32(name, convert);
        }

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToInt32来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public int GetInt32(int ordinal, int defaultValue, bool convert)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetInt32(ordinal, convert);
        }

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public int? GetInt32Null(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetInt32(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回int
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public int? GetInt32Null(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetInt32(ordinal);
        }
        #endregion

        #region GetInt64

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public long GetInt64(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetInt64(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public long GetInt64(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetInt64(ordinal);
        }

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="convert">是否使用Convert.ToInt64来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public long GetInt64(string name, bool convert)
        {
            CheckFieldNotNull(name);
            if (convert)
            {
                return Convert.ToInt64(this[this.GetOrdinal(name)]);
            }
            else
            {
                return GetInt64(name);
            }
        }

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="convert">是否使用Convert.ToInt64来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public long GetInt64(int ordinal, bool convert)
        {
            CheckFieldNotNull(ordinal);
            if (convert)
            {
                return Convert.ToInt64(this[ordinal]);
            }
            else
            {
                return GetInt64(ordinal);
            }
        }

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public long GetInt64(string name, long defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetInt64(name);
        }

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public long GetInt64(int ordinal, long defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetInt64(ordinal);
        }

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToInt64来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public long GetInt64(string name, long defaultValue, bool convert)
        {
            return this.IsDBNull(name) ? defaultValue : GetInt64(name, convert);
        }

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToInt64来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public long GetInt64(int ordinal, long defaultValue, bool convert)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetInt64(ordinal, convert);
        }

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public long? GetInt64Null(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetInt64(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回Int64
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public long? GetInt64Null(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetInt64(ordinal);
        }
        #endregion

        #region GetFloat

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public float GetFloat(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetFloat(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public float GetFloat(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetFloat(ordinal);
        }

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="convert">是否使用Convert.ToSingle来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public float GetFloat(string name, bool convert)
        {
            CheckFieldNotNull(name);
            if (convert)
            {
                return Convert.ToFloat(this[this.GetOrdinal(name)]);
            }
            else
            {
                return GetFloat(name);
            }
        }

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="convert">是否使用Convert.ToSingle来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public float GetFloat(int ordinal, bool convert)
        {
            CheckFieldNotNull(ordinal);
            if (convert)
            {
                return Convert.ToFloat(this[ordinal]);
            }
            else
            {
                return GetFloat(ordinal);
            }
        }

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public float GetFloat(string name, float defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetFloat(name);
        }

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public float GetFloat(int ordinal, float defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetFloat(ordinal);
        }

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToSingle来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public float GetFloat(string name, float defaultValue, bool convert)
        {
            return this.IsDBNull(name) ? defaultValue : GetFloat(name, convert);
        }

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToSingle来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public float GetFloat(int ordinal, float defaultValue, bool convert)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetFloat(ordinal, convert);
        }

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public float? GetFloatNull(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetFloat(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回float
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public float? GetFloatNull(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetFloat(ordinal);
        }

        #endregion

        #region GetDouble

        /// <summary>
        /// 返回double
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public double GetDouble(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetDouble(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回double
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public double GetDouble(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetDouble(ordinal);
        }

        /// <summary>
        /// 返回double
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="convert">是否使用Convert.ToDouble来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public double GetDouble(string name, bool convert)
        {
            CheckFieldNotNull(name);
            if (convert)
            {
                return Convert.ToDouble(this[this.GetOrdinal(name)]);
            }
            else
            {
                return GetDouble(name);
            }
        }

        /// <summary>
        /// 返回double
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="convert">是否使用Convert.ToDouble来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public double GetDouble(int ordinal, bool convert)
        {
            CheckFieldNotNull(ordinal);
            if (convert)
            {
                return Convert.ToDouble(this[ordinal]);
            }
            else
            {
                return GetDouble(ordinal);
            }
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public double GetDouble(string name, double defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetDouble(name);
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public double GetDouble(int ordinal, double defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetDouble(ordinal);
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToDecimal来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public double GetDouble(string name, double defaultValue, bool convert)
        {
            return this.IsDBNull(name) ? defaultValue : GetDouble(name, convert);
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToDecimal来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public double GetDouble(int ordinal, double defaultValue, bool convert)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetDouble(ordinal, convert);
        }

        /// <summary>
        /// 返回double
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public double? GetDoubleNull(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetDouble(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回double
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public double? GetDoubleNull(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetDouble(ordinal);
        }
        #endregion

        #region GetDecimal

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public decimal GetDecimal(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetDecimal(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public decimal GetDecimal(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetDecimal(ordinal);
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="convert">是否使用Convert.ToDecimal来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public decimal GetDecimal(string name, bool convert)
        {
            CheckFieldNotNull(name);
            if (convert)
            {
                return Convert.ToDecimal(this[this.GetOrdinal(name)]);
            }
            else
            {
                return GetDecimal(name);
            }
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="convert">是否使用Convert.ToDecimal来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public decimal GetDecimal(int ordinal, bool convert)
        {
            CheckFieldNotNull(ordinal);
            if (convert)
            {
                return Convert.ToDecimal(this[ordinal]);
            }
            else
            {
                return GetDecimal(ordinal);
            }
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public decimal GetDecimal(string name, decimal defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetDecimal(name);
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public decimal GetDecimal(int ordinal, decimal defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetDecimal(ordinal);
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToDecimal来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public decimal GetDecimal(string name, decimal defaultValue, bool convert)
        {
            return this.IsDBNull(name) ? defaultValue : GetDecimal(name, convert);
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToDecimal来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public decimal GetDecimal(int ordinal, decimal defaultValue, bool convert)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetDecimal(ordinal, convert);
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public decimal? GetDecimalNull(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            };
            return this.dr.GetDecimal(this.GetOrdinal(name));
        }

        /// <summary>
        /// 返回decimal
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public decimal? GetDecimalNull(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetDecimal(ordinal);
        }
        #endregion

        #region GetDateTime

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public DateTime GetDateTime(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetDateTime(this.dr.GetOrdinal(name));
        }

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public DateTime GetDateTime(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetDateTime(ordinal);
        }

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="convert">是否使用Convert.ToDateTime来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public DateTime GetDateTime(string name, bool convert)
        {
            CheckFieldNotNull(name);
            if (convert)
            {
                return Convert.ToDateTime(this[this.GetOrdinal(name)]);
            }
            else
            {
                return GetDateTime(name);
            }
        }

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="convert">是否使用Convert.ToDateTime来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public DateTime GetDateTime(int ordinal, bool convert)
        {
            CheckFieldNotNull(ordinal);
            if (convert)
            {
                return Convert.ToDateTime(this[ordinal]);
            }
            else
            {
                return GetDateTime(ordinal);
            }
        }

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public DateTime GetDateTime(string name, DateTime defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : GetDateTime(name);
        }

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public DateTime GetDateTime(int ordinal, DateTime defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetDateTime(ordinal);
        }

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToDateTime来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public DateTime GetDateTime(string name, DateTime defaultValue, bool convert)
        {
            return this.IsDBNull(name) ? defaultValue : GetDateTime(name, convert);
        }

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToDateTime来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public DateTime GetDateTime(int ordinal, DateTime defaultValue, bool convert)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetDateTime(ordinal, convert);
        }

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public DateTime? GetDateTimeNull(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetDateTime(this.dr.GetOrdinal(name));
        }

        /// <summary>
        /// 返回DateTime
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public DateTime? GetDateTimeNull(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetDateTime(ordinal);
        }
        #endregion

        #region GetGuid

        /// <summary>
        /// 返回Guid
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public Guid GetGuid(string name)
        {
            CheckFieldNotNull(name);
            return this.dr.GetGuid(this.dr.GetOrdinal(name));
        }

        /// <summary>
        /// 返回Guid
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public Guid GetGuid(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return this.dr.GetGuid(ordinal);
        }

        /// <summary>
        /// 返回Guid
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public Guid GetGuid(string name, Guid defaultValue)
        {
            return this.IsDBNull(name) ? defaultValue : this.dr.GetGuid(this.dr.GetOrdinal(name));
        }

        /// <summary>
        /// 返回Guid
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public Guid GetGuid(int ordinal, Guid defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : this.dr.GetGuid(ordinal);
        }

        /// <summary>
        /// 返回Guid
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public Guid? GetGuidNull(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetGuid(this.dr.GetOrdinal(name));
        }

        /// <summary>
        /// 返回Guid
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public Guid? GetGuidNull(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetGuid(ordinal);
        }

        #endregion

        #region GetString

        /// <summary>
        /// 返回字符串
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>要查找的列的值</returns>
        public string GetString(string name)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            return this.dr.GetString(this.dr.GetOrdinal(name));
        }

        /// <summary>
        /// 返回字符串
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>要查找的列的值</returns>
        public string GetString(int ordinal)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            return this.dr.GetString(ordinal);
        }

        /// <summary>
        /// 返回字符串
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="convert">是否使用Convert.ToString来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public string GetString(string name, bool convert)
        {
            if (this.IsDBNull(name))
            {
                return null;
            }
            if (convert)
            {
                return Convert.ToString(this[this.GetOrdinal(name)]);
            }
            else
            {
                return GetString(name);
            }
        }

        /// <summary>
        /// 返回字符串
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="convert">是否使用Convert.ToString来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public string GetString(int ordinal, bool convert)
        {
            if (this.IsDBNull(ordinal))
            {
                return null;
            }
            if (convert)
            {
                return Convert.ToString(this[ordinal]);
            }
            else
            {
                return GetString(ordinal);
            }
        }

        /// <summary>
        /// 返回字符串
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public string GetString(string name, string defaultValue)
        {
            return (this.IsDBNull(name) ? defaultValue : this.GetString(name));
        }

        /// <summary>
        /// 返回字符串
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>要查找的列的值</returns>
        public string GetString(int ordinal, string defaultValue)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetString(ordinal);
        }

        /// <summary>
        /// 返回字符串
        /// </summary>
        /// <param name="name">列名</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToString来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public string GetString(string name, string defaultValue, bool convert)
        {
            return this.IsDBNull(name) ? defaultValue : GetString(name, convert);
        }

        /// <summary>
        /// 返回字符串
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="convert">是否使用Convert.ToString来转换返回的结果</param>
        /// <returns>要查找的列的值</returns>
        public string GetString(int ordinal, string defaultValue, bool convert)
        {
            return this.IsDBNull(ordinal) ? defaultValue : GetString(ordinal, convert);
        }

        #endregion

        #region GetValue

        /// <summary>
        /// 返回指定列的值
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns></returns>
        public object GetValue(string name)
        {
            CheckFieldNotNull(name);
            return dr.GetValue(dr.GetOrdinal(name));
        }

        /// <summary>
        /// 返回指定列的值
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns></returns>
        public object GetValue(int ordinal)
        {
            CheckFieldNotNull(ordinal);
            return dr.GetValue(ordinal);
        }

        #endregion

        #region GetFieldType

        /// <summary>
        /// 获取指定列的数据类型
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns></returns>
        public Type GetFieldType(int ordinal)
        {
            return this.dr.GetFieldType(ordinal);
        }

        /// <summary>
        /// 获取指定列的数据类型
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns></returns>
        public Type GetFieldType(string name)
        {
            return this.dr.GetFieldType(this.dr.GetOrdinal(name));
        }

        #endregion

        /// <summary>
        /// 数据读取器的字段个数
        /// </summary>
        public int FieldCount
        {
            get
            {
                return dr.FieldCount;
            }
        }

        /// <summary>
        /// 返回一个值,指示检索到的结果中是否包含行结果.
        /// <para>
        /// 如果数据读取器不支持此操作,则抛出一个异常
        /// </para>
        /// </summary>
        public bool HasRows
        {
            get
            {
                if (this.dbdr != null)
                {
                    return this.dbdr.HasRows;
                }
                return (bool)this.dr.GetType().GetProperty("HasRows").GetValue(this.dr, null);
            }
        }

        /// <summary>
        /// 当读取批处理 Transact-SQL 语句的结果时，使数据读取器前进到下一个结果
        /// </summary>
        /// <returns></returns>
        public bool NextResult()
        {
            this.rowidx = -1;
            return !dr.IsClosed && dr.NextResult();
        }

        /// <summary>
        /// 获取结果集的构架信息
        /// </summary>
        /// <returns>结果集的构架信息</returns>
        public DataTable GetSchemaTable()
        {
            return this.dr.GetSchemaTable();
        }

        /// <summary>
        /// 返回受影响的行数
        /// </summary>
        public int RecordsAffected
        {
            get
            {
                return dr.RecordsAffected;
            }
        }

        /// <summary>
        /// 获取一个值，用于指示当前行的嵌套深度
        /// </summary>
        public int Depth
        {
            get
            {
                return dr.Depth;
            }
        }

        /// <summary>
        /// 检查数据读取器是否已关闭
        /// </summary>
        public bool IsClosed
        {
            get
            {
                return dr.IsClosed;
            }
        }

        /// <summary>
        /// 检查某一列是否是DBNull值
        /// </summary>
        /// <param name="name">列名</param>
        /// <returns>返回一个值,指示获取的列是否为NULL</returns>
        public bool IsDBNull(string name)
        {
            return dr.IsDBNull(this.GetOrdinal(name));
        }

        /// <summary>
        /// 检查某一列是否是DBNull值
        /// </summary>
        /// <param name="ordinal">列编号</param>
        /// <returns>返回一个值,指示获取的列是否为NULL</returns>
        public bool IsDBNull(int ordinal)
        {
            return dr.IsDBNull(ordinal);
        }

        /// <summary>
        /// 关闭DataReader
        /// </summary>
        public void Close()
        {
            this.dr.Close();
        }

        /// <summary>
        /// 获取位于指定索引处的列。
        /// </summary>
        /// <param name="index">要获取的列的从零开始的索引</param>
        /// <returns>作为 Object 位于指定索引处的列</returns>
        public object this[int index]
        {
            get
            {
                return dr[index];
            }
        }

        private System.Text.StringBuilder sbdesc = null;
        /// <summary>
        /// 获取结果集的描述信息
        /// </summary>
        /// <returns>结果集的描述信息</returns>
        public string Description
        {
            get
            {
                if (sbdesc == null)
                {
                    sbdesc = new System.Text.StringBuilder();

                    sbdesc.AppendLine("数据库命令描述信息如下");
                    sbdesc.AppendLine("命令    :" + CommandText);
                    sbdesc.AppendLine("类型    :" + CommandType);
                    int max = 0;
                    if (Parameters.Count > 0)
                    {
                        sbdesc.AppendLine("参数    :");
                        foreach (IDataParameter p in Parameters)
                        {
                            max = p.ParameterName.Length > max ? p.ParameterName.Length : max;
                        }
                        foreach (IDataParameter p in Parameters)
                        {
                            if (p.DbType == DbType.DateTime)
                            {
                                sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), ((DateTime)p.Value).ToString("yyyy-MM-dd HH:mm:ss.fff"));
                            }
                            else
                            {
                                sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), p.Value);
                            }
                        }
                    }
                    max = 0;
                    if (dr.FieldCount > 0)
                    {
                        sbdesc.AppendLine("字段个数:" + dr.FieldCount.ToString());
                        sbdesc.AppendLine("字段列表:");
                        for (int i = 0; i < dr.FieldCount; i++)
                        {
                            max = dr.GetName(i).Length > max ? dr.GetName(i).Length : max;
                        }
                        for (int i = 0; i < dr.FieldCount; i++)
                        {
                            sbdesc.AppendFormatLine("{0}:{1}", dr.GetName(i).PadRight(max, ' '), dr.GetDataTypeName(i));
                        }
                    }
                }
                return sbdesc.ToString();
            }
        }

        /// <summary>
        /// 获取具有指定名称的列。
        /// </summary>
        /// <param name="name">要查找的列的名称。</param>
        /// <returns>名称指定为 Object 的列。</returns>
        public object this[string name]
        {
            get
            {
                return dr[this.GetOrdinal(name)];
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public new void Dispose()
        {
            if (!this.dr.IsClosed)
            {
                this.dr.Close();
            }
            this.dr.Dispose();
            base.Dispose();
        }

        /// <summary>
        /// 从数据读取器里读取一个指定类型的对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <returns>返回读取的对象,如是没有读取到,返回null</returns>
        public T ReadEntity<T>()
            where T : BaseEntity, new()
        {
            T result = null;
            if (this.Read())
            {
                result = new T();
                EntityHelper.SetObjectProperty(result, this);
            }
            return result;
        }

        /// <summary>
        /// 从数据读取器里读取一个指定类型的对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="args">构造函数的参数</param>
        /// <returns>返回读取的对象,如是没有读取到,返回null</returns>
        public T ReadEntity<T>(object[] args)
            where T : BaseEntity
        {
            T result = null;
            if (this.Read())
            {
                result = PTA.Reflect.CreateInstance<T>(args);
                EntityHelper.SetObjectProperty(result, this);
            }
            return result;
        }


        /// <summary>
        /// 使用数据读取器填充一个对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">要填充的对象</param>
        /// <returns>返回填充的对象</returns>
        public T FillEntity<T>(T t)
            where T : BaseEntity
        {
            if (t == null)
            {
                throw new ArgumentNullException("t");
            }
            EntityHelper.SetObjectProperty(t, this);
            return t;
        }

        /// <summary>
        /// 从数据读取器里读取指定类型的对象数组
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="count">读取数据数量</param>
        /// <returns>返回读取的对象列表,如是没有读取到,返回一个空的对象列表</returns>
        public List<T> ReadEntityArray<T>(int count = 0)
             where T : BaseEntity, new()
        {
            List<T> result = new List<T>();
            int index = 0;
            var fields = new Dictionary<string, EntityPropertyInfo>();
            foreach (var p in EntityHelper.GetEntityAttribute(typeof(T)).Properties)
            {
                if (this.HasField(p.Value.PropertyAttribute.Name))
                {
                    fields.Add(p.Value.PropertyAttribute.Name, p.Value);
                }
            }
            while (this.Read() && (count == 0 || index < count))
            {
                T item = new T();
                EntityHelper.SetObjectProperty(item, this, fields);
                result.Add(item);
                ++index;
            }
            return result;
        }

        /// <summary>
        /// 从数据读取器里读取指定类型的对象数组
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="count">读取数据数量</param>
        /// <param name="args">构造函数的参数</param>
        /// <returns>返回读取的对象列表,如是没有读取到,返回一个空的对象列表</returns>
        public List<T> ReadEntityArray<T>(object[] args, int count = 0)
             where T : BaseEntity
        {
            List<T> result = new List<T>();
            int index = 0;
            var fields = new Dictionary<string, EntityPropertyInfo>();
            foreach (var p in EntityHelper.GetEntityAttribute(typeof(T)).Properties)
            {
                if (this.HasField(p.Value.PropertyAttribute.Name))
                {
                    fields.Add(p.Value.PropertyAttribute.Name, p.Value);
                }
            }
            while (this.Read() && (count == 0 || index < count))
            {
                T item = PTA.Reflect.CreateInstance<T>(args);
                EntityHelper.SetObjectProperty(item, this, fields);
                result.Add(item);
                ++index;
            }
            return result;
        }

        #region IEnumerable Members

        /// <summary>
        /// 遍历数据读取器
        /// </summary>
        /// <returns></returns>
        public IEnumerator GetEnumerator()
        {
            //DbEnumerator有一个重载的构造函数,如果使用DbEnumerator(IDataReader reader, bool closeReader)的话,如果后面的参数为true,则游标指定到第一个结果
            //集的最后一个结果时,会自动关闭.
            return new DbEnumerator(this.dr);
        }

        #endregion

        public IDataReader GetData(int i)
        {
            return dr.GetData(i);
        }

        public string GetDataTypeName(int i)
        {
            return dr.GetDataTypeName(i);
        }

        public string GetDataTypeName(string name)
        {
            return dr.GetDataTypeName(this.GetOrdinal(name));
        }

        public int GetValues(object[] values)
        {
            return dr.GetValues(values);
        }
    }
    #endregion
    #endregion

    #region DataAttribute
    /// <summary>
    /// 实体属性信息
    /// </summary>
    internal class EntityPropertyInfo
    {
        public ColumnAttribute PropertyAttribute;
        public PropertyInfo PropertyInfo;
    }

    /// <summary>
    /// 实体信息
    /// </summary>
    internal class EntityInfo
    {
        /// <summary>
        /// 实体名称
        /// </summary>
        internal string EntityName
        {
            get;
            set;
        }

        /// <summary>
        /// 实体存储表名
        /// </summary>
        internal string DataTable
        {
            get;
            set;
        }

        private Dictionary<string, EntityPropertyInfo> properties = new Dictionary<string, EntityPropertyInfo>();
        /// <summary>
        /// 实体键列表
        /// </summary>
        internal Dictionary<string, EntityPropertyInfo> Properties
        {
            get
            {
                return this.properties;
            }
        }
    }

    internal class EntityHelper
    {
        private static Dictionary<string, EntityInfo> dict = new Dictionary<string, EntityInfo>();
        private static object lockObj = new object();

        /// <summary>
        /// 获取一个类型的特性
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type"></param>
        internal static EntityInfo GetEntityAttribute(Type t)
        {
            if (dict.ContainsKey(t.Name))
            {
                return dict[t.Name];
            }
            lock (lockObj)
            {
                if (dict.ContainsKey(t.Name))
                {
                    return dict[t.Name];
                }
                else
                {
                    EntityInfo result = new EntityInfo();
                    result.EntityName = t.Name;
                    if (t.IsDefined(typeof(TableAttribute), true))
                    {
                        TableAttribute attr = t.GetCustomAttributes(typeof(TableAttribute), true)[0] as TableAttribute;
                        result.DataTable = String.IsNullOrWhiteSpace(attr.Name) ? t.Name : attr.Name;
                    }
                    else
                    {
                        result.DataTable = t.Name;
                    }
                    foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public))
                    {
                        if (pi.IsDefined(typeof(ColumnAttribute), true))
                        {
                            ColumnAttribute dpa = pi.GetCustomAttributes(typeof(ColumnAttribute), true)[0] as ColumnAttribute;
                            EntityPropertyInfo epi = new EntityPropertyInfo() { };
                            epi.PropertyAttribute = pi.GetCustomAttributes(typeof(ColumnAttribute), true)[0] as ColumnAttribute;
                            epi.PropertyInfo = pi;
                            if (String.IsNullOrWhiteSpace(epi.PropertyAttribute.Name))
                            {
                                epi.PropertyAttribute.Name = pi.Name;
                            }
                            result.Properties.Add(pi.Name, epi);
                        }
                    }
                    if (result.Properties.Count == 0)
                    {
                        throw new Exception(string.Format("数据类型:{0} 在插入时无数据可加,请添加", t.FullName));
                    }
                    dict.Add(t.Name, result);
                    return result;
                }
            }
        }

        /// <summary>
        /// 从数据读取器中读取一个对象
        /// </summary>
        /// <param name="m"></param>
        /// <param name="dr"></param>
        internal static void SetObjectProperty(BaseEntity m, DataReader dr, Dictionary<string, EntityPropertyInfo> fields = null)
        {
            m.FromDbFill = true;
            if (fields == null)
            {
                fields = new Dictionary<string, EntityPropertyInfo>();
                foreach (var p in EntityHelper.GetEntityAttribute(m.GetType()).Properties)
                {
                    if (dr.HasField(p.Value.PropertyAttribute.Name))
                    {
                        fields.Add(p.Value.PropertyAttribute.Name, p.Value);
                    }
                }
            }
            foreach (var item in fields)
            {
                object value = ToEntityValue(item.Value.PropertyInfo.PropertyType, dr[item.Value.PropertyAttribute.Name]);
                if (value != null)
                {
                    if (item.Value.PropertyInfo.CanWrite)
                    {
                        item.Value.PropertyInfo.SetValue(m, PTA.Convert.ChangeType(value, item.Value.PropertyInfo.PropertyType), null);
                    }
                    else
                    {
                        if (item.Value.PropertyInfo.PropertyType == typeof(List<int>))
                        {
                            ((List<int>)item.Value.PropertyInfo.GetValue(m, null)).AddRange((List<int>)value);
                            continue;
                        }
                        if (item.Value.PropertyInfo.PropertyType == typeof(List<long>))
                        {
                            ((List<long>)item.Value.PropertyInfo.GetValue(m, null)).AddRange((List<long>)value);
                            continue;
                        }
                        if (item.Value.PropertyInfo.PropertyType == typeof(List<string>))
                        {
                            ((List<string>)item.Value.PropertyInfo.GetValue(m, null)).AddRange((List<string>)value);
                            continue;
                        }
                    }
                }
            }
            m.FromDbFill = false;
        }

        /// <summary>
        /// 把数据库的数据转换为实体的数据
        /// </summary>
        /// <param name="type">实体的数据类型</param>
        /// <param name="data">数据库字段的值</param>
        /// <returns>实体的数据</returns>
        private static object ToEntityValue(Type type, object data)
        {
            if (PTA.Convert.IsDBNull(data))
            {
                return null;
            }
            else
            {
                if (type.IsValueType || type == typeof(string))
                {
                    return data;
                }
                if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    type = new System.ComponentModel.NullableConverter(type).UnderlyingType;
                    return Convert.ChangeType(data, type);
                }

                #region Array
                if ((type.IsArray && type != typeof(byte[])) || (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(List<>))))
                {
                    if (type == typeof(int[]) || type == typeof(List<int>))
                    {
                        List<int> result = PTA.Convert.FromStrictString<int>(data.ToString());
                        if (type == typeof(int[]))
                        {
                            return result.ToArray();
                        }
                        return result;
                    }
                    if (type == typeof(long[]) || type == typeof(List<long>))
                    {
                        List<long> result = PTA.Convert.FromStrictString<long>(data.ToString());
                        if (type == typeof(long[]))
                        {
                            return result.ToArray();
                        }
                        return result;
                    }
                    if (type == typeof(string[]) || type == typeof(List<string>))
                    {
                        List<string> result = PTA.Convert.FromStrictString<string>(data.ToString());
                        if (type == typeof(string[]))
                        {
                            return result.ToArray();
                        }
                        return result;
                    }
                }
                #endregion

                return data;
            }
        }

        internal static void SetObjectProperty(BaseEntity m, DataRow dr)
        {
            m.FromDbFill = true;
            EntityInfo ea = EntityHelper.GetEntityAttribute(m.GetType());
            foreach (var item in ea.Properties)
            {
                if (dr[item.Value.PropertyAttribute.Name] == null)
                {
                    continue;
                }
                object value = ToEntityValue(item.Value.PropertyInfo.PropertyType, dr[item.Value.PropertyAttribute.Name]);
                if (value != null)
                {
                    if (item.Value.PropertyInfo.CanWrite)
                    {
                        item.Value.PropertyInfo.SetValue(m, PTA.Convert.ChangeType(value, item.Value.PropertyInfo.PropertyType), null);
                    }
                    else
                    {
                        if (item.Value.PropertyInfo.PropertyType == typeof(List<int>))
                        {
                            ((List<int>)item.Value.PropertyInfo.GetValue(m, null)).AddRange((List<int>)value);
                            continue;
                        }
                        if (item.Value.PropertyInfo.PropertyType == typeof(List<long>))
                        {
                            ((List<long>)item.Value.PropertyInfo.GetValue(m, null)).AddRange((List<long>)value);
                            continue;
                        }
                        if (item.Value.PropertyInfo.PropertyType == typeof(List<string>))
                        {
                            ((List<string>)item.Value.PropertyInfo.GetValue(m, null)).AddRange((List<string>)value);
                            continue;
                        }
                    }
                }
            }
            m.FromDbFill = false;
        }
    }

    /// <summary>
    /// 对象属性的绑定标志，标识出该属性会出现在Insert、Update或Where中，当然也可以指定为None，不出现在SQL中
    /// </summary>
    [Flags]
    public enum BindingFlag
    {
        /// <summary>
        /// 表示属性会出现在Insert中
        /// </summary>
        Insert = 1,

        /// <summary>
        /// 表示属性会出现在Update中
        /// </summary>
        Update = 2,

        /// <summary>
        /// 表示属性会出现在查询的返回字段中
        /// </summary>
        Select = 4
    }

    public enum ColumnType
    {
        /// <summary>
        /// 默认,使用属性的数据类型
        /// </summary>
        Default,

        /// <summary>
        /// 将属性序列化为XML保存
        /// </summary>
        Xml,

        /// <summary>
        /// 将属性序列化为JSON保存
        /// </summary>
        Json
    }

    public class TableAttribute : Attribute
    {
        public TableAttribute() { }
        public TableAttribute(string name) { this.Name = name; }
        public string Name { get; set; }
    }

    /// <summary>
    /// 字段特性
    /// </summary>
    public class ColumnAttribute : Attribute
    {
        #region Private
        private BindingFlag flags = BindingFlag.Insert | BindingFlag.Select | BindingFlag.Update;
        #endregion

        public ColumnAttribute() { this.DbType = ColumnType.Default; }
        public ColumnAttribute(string name) { this.Name = name; this.DbType = ColumnType.Default; }
        public ColumnType DbType { get; set; }
        public string Expression { get; set; }
        public bool PrimaryKey { get; set; }
        public string Name { get; set; }
        /// <summary>
        /// 对使用Identity的数据库有效
        /// </summary>
        public bool Identity { get; set; }
        /// <summary>
        /// 对使用序列的数据库有效
        /// </summary>
        public string SequenceName { get; set; }
        public BindingFlag Flag
        {
            get
            {
                return flags;
            }
            set
            {
                flags = value;
            }
        }
    }
    #endregion

    #region DataCommand

    public interface IDataCommand<P> where P : class, System.Data.IDbDataParameter, new()
    {
        P Add(P p);
        P Add(string name, object value, System.Data.DbType type, System.Data.ParameterDirection direction, int size);
        P AddIn(string name, System.Data.DbType type);
        P AddIn(string name, System.Data.DbType type, int size);
        P AddIn(string name, System.Data.DbType type, int size, object value);
        P AddIn(string name, System.Data.DbType type, object value);
        P AddIn(string name, object value);
        P AddOut(string name);
        P AddOut(string name, System.Data.DbType type);
        P AddOut(string name, System.Data.DbType type, int size);
        void AddRange(P[] parameters);
        P AddReturn(string name);
        P AddReturn(string name, System.Data.DbType type);
        P AddReturn(string name, System.Data.DbType type, int size);
        void ClearParameters();
        string CommandText { get; set; }
        System.Data.CommandType CommandType { get; set; }
        bool Contains(string name);
        string Description { get; }
        P[] Parameters { get; }
        P this[string name] { get; }
    }

    /// <summary>
    /// 一个执行数据库命令的Command接口
    /// </summary>
    /// <typeparam name="P">数据命令参数类型</typeparam>
    public abstract class DataCommand<P> : PTA.Db.IDataCommand<P>
        where P : class, IDbDataParameter, new()
    {
        /// <summary>
        /// 数据库命令参数前缀(如SqlServer数据库为@)
        /// </summary>
        protected abstract string ParameterPrefix
        {
            get;
        }
        public DataCommand()
        {
        }

        /// <summary>
        /// 创建一个数据库命令,这个构造函数会根据命令中是否有空格来确定是SQL文本还是存储过程(存储过程命令不包含空格)
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        public DataCommand(string commandText)
        {
            this.commandText = commandText;
            this.commandType = commandText.Contains(" ") ? System.Data.CommandType.Text : System.Data.CommandType.StoredProcedure;
        }

        public DataCommand(string commandText, CommandType commandType)
        {
            this.commandText = commandText;
            this.commandType = commandType;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="parameters">数据库命令参数</param>
        public DataCommand(string commandText, CommandType commandType, P[] parameters)
        {
            this.commandText = commandText;
            this.commandType = commandType;
            if (parameters != null && parameters.Length > 0)
            {
                this.parameters.AddRange(parameters);
            }
        }

        protected List<P> parameters = new List<P>();
        /// <summary>
        /// 命令参数
        /// </summary>
        public P[] Parameters
        {
            get
            {
                return parameters.ToArray();
            }
        }

        /// <summary>
        /// 返回指定名称的参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <returns>参数</returns>
        public P this[string name]
        {
            get
            {
                return parameters.Find(item => item.ParameterName.Equals(WrapParameterName(name), StringComparison.OrdinalIgnoreCase));
            }
        }

        /// <summary>
        /// 检查是否包含某个指定名称的参数
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool Contains(string name)
        {
            if (parameters != null)
            {
                return parameters.Exists(x => x.ParameterName.Equals(WrapParameterName(name), StringComparison.OrdinalIgnoreCase));
            }
            return false;
        }

        private string commandText = string.Empty;
        /// <summary>
        /// 数据库命令
        /// </summary>
        public virtual string CommandText
        {
            get
            {
                return this.commandText;
            }
            set
            {
                this.commandText = value;
            }
        }

        private CommandType commandType = CommandType.Text;
        /// <summary>
        /// 数据库命令的类型
        /// </summary>
        public virtual CommandType CommandType
        {
            get
            {
                return commandType;
            }
            set
            {
                this.commandType = value;
            }
        }

        /// <summary>
        /// 清空参数
        /// </summary>
        public void ClearParameters()
        {
            this.parameters.Clear();
        }

        public string Description
        {
            get
            {
                StringBuilder sbdesc = new StringBuilder();
                sbdesc.AppendLine("命令类型:" + CommandType);
                sbdesc.AppendLine("命令文本:" + CommandText);
                if (Parameters != null && Parameters.Length > 0)
                {
                    sbdesc.AppendLine("参数列表:");
                    int max = 0;
                    foreach (IDataParameter p in Parameters)
                    {
                        max = p.ParameterName.Length > max ? p.ParameterName.Length : max;
                    }
                    foreach (IDataParameter p in Parameters)
                    {
                        sbdesc.AppendFormatLine("{0} : {1} = {2}", p.ParameterName.PadRight(max, ' '), p.Direction.ToString().PadRight(11, ' '), p.Value);
                    }
                }
                return sbdesc.ToString();
            }
        }

        public P Add(P p)
        {
            this.parameters.Add(p);
            return p;
        }

        public void AddRange(P[] parameters)
        {
            if (parameters != null && parameters.Length > 0)
            {
                this.parameters.AddRange(parameters);
            }
        }

        public P Add(string name, object value, DbType type, ParameterDirection direction, int size)
        {
            var p = new P() { ParameterName = WrapParameterName(name), DbType = type, Size = size, Direction = direction, Value = value };
            this.Add(p);
            return p;
        }

        public P AddIn(string name, DbType type)
        {
            var p = new P() { ParameterName = WrapParameterName(name), DbType = type };
            this.Add(p);
            return p;
        }

        public virtual P AddIn(string name, object value)
        {
            P p = new P();
            p.ParameterName = WrapParameterName(name);
            p.Value = value;
            p.Direction = ParameterDirection.Input;
            this.parameters.Add(p);
            return p;
        }

        public P AddIn(string name, DbType type, object value)
        {
            P p = new P();
            p.ParameterName = WrapParameterName(name);
            p.Value = value;
            p.DbType = type;
            p.Direction = ParameterDirection.Input;
            this.parameters.Add(p);
            return p;
        }

        public P AddIn(string name, DbType type, int size)
        {
            var p = new P() { ParameterName = WrapParameterName(name), DbType = type, Size = size };
            this.Add(p);
            return p;
        }

        public P AddIn(string name, DbType type, int size, object value)
        {
            var p = new P() { ParameterName = WrapParameterName(name), DbType = type, Size = size, Value = value };
            this.Add(p);
            return p;
        }

        public P AddOut(string name)
        {
            P p = new P();
            p.ParameterName = WrapParameterName(name);
            p.Direction = ParameterDirection.Output;
            this.parameters.Add(p);
            return p;
        }

        public P AddOut(string name, DbType type)
        {
            P p = new P();
            p.ParameterName = WrapParameterName(name);
            p.Direction = ParameterDirection.Output;
            p.DbType = type;
            this.parameters.Add(p);
            return p;
        }

        public P AddOut(string name, DbType type, int size)
        {
            var p = new P() { ParameterName = WrapParameterName(name), DbType = type, Size = size, Direction = ParameterDirection.Output };
            this.parameters.Add(p);
            return p;
        }

        public P AddReturn(string name)
        {
            P p = new P();
            p.ParameterName = WrapParameterName(name);
            p.Direction = ParameterDirection.ReturnValue;
            this.parameters.Add(p);
            return p;
        }

        public P AddReturn(string name, DbType type)
        {
            P p = new P();
            p.ParameterName = WrapParameterName(name);
            p.Direction = ParameterDirection.ReturnValue;
            p.DbType = type;
            this.parameters.Add(p);
            return p;
        }

        public P AddReturn(string name, DbType type, int size)
        {
            var p = new P() { ParameterName = WrapParameterName(name), DbType = type, Size = size, Direction = ParameterDirection.ReturnValue };
            this.parameters.Add(p);
            return p;
        }

        protected string WrapParameterName(string name)
        {
            return (!string.IsNullOrWhiteSpace(this.ParameterPrefix) && !name.StartsWith(this.ParameterPrefix)) ? this.ParameterPrefix + name : name;
        }
    }

    #endregion

    #region 分页查询检索条件
    public interface IPageSearch<P> : IDataCommand<P>
          where P : class, System.Data.IDbDataParameter, new()
    {
        void And(string sql, params string[] args);
        string FieldsName { get; set; }
        OrderFieldCollection OrderField { get; }
        int PageCount { get; }
        int PageIndex { get; set; }
        int PageSize { get; set; }
        string PrimaryKey { get; set; }
        string TableName { get; set; }
        int TotalCount { get; set; }
        string Where { get; }
    }

    /// <summary>
    /// 排序字段集合
    /// </summary>
    public class OrderFieldCollection
    {
        List<KeyValuePair<string, OrderType>> dict = null;

        /// <summary>
        /// 添加排序字段,默认使用升序
        /// </summary>
        /// <param name="field"></param>
        public void Add(string field)
        {
            this.Add(field, OrderType.ASC);
        }

        /// <summary>
        /// 添加一个排序字段
        /// </summary>
        /// <param name="field">排序字段</param>
        /// <param name="type">排序类型</param>
        public void Add(string field, OrderType type)
        {
            if (dict == null)
            {
                dict = new List<KeyValuePair<string, OrderType>>();
            }
            for (int i = 0; i < dict.Count; i++)
            {
                if (dict[i].Key.Equals(field, StringComparison.OrdinalIgnoreCase))
                {
                    dict[i] = new KeyValuePair<string, OrderType>(field.ToUpper(), type);
                    return;
                }
            }
            dict.Add(new KeyValuePair<string, OrderType>(field.ToUpper(), type));
        }

        /// <summary>
        /// 移除一个排序字段
        /// </summary>
        /// <param name="field"></param>
        public void Remove(string field)
        {
            for (int i = 0; i < dict.Count; i++)
            {
                if (dict[i].Key.Equals(field, StringComparison.OrdinalIgnoreCase))
                {
                    dict.RemoveAt(i);
                }
            }
        }

        /// <summary>
        /// 移除一个排序字段
        /// </summary>
        /// <param name="index">要移除的排序字段的索引</param>
        public void Remove(int index)
        {
            if (dict == null || index >= dict.Count)
            {
                return;
            }
            dict.RemoveAt(index);
        }

        /// <summary>
        /// 把一个要排序的字段放到最前面
        /// </summary>
        /// <param name="field"></param>
        public void MoveFirst(string field)
        {
            for (int i = 0; i < dict.Count; i++)
            {
                if (dict[i].Key.Equals(field, StringComparison.OrdinalIgnoreCase))
                {
                    KeyValuePair<string, OrderType> item = dict[i];
                    dict.RemoveAt(i);
                    dict.Insert(0, item);
                }
            }
        }

        /// <summary>
        /// 将排序字段列表中指定位置的排序字段移动到最前面
        /// </summary>
        /// <param name="index">要移动到最前面的排序字段的索引</param>
        public void MoveFirst(int index)
        {
            if (dict == null || index >= dict.Count || index == 0)
            {
                return;
            }
            KeyValuePair<string, OrderType> item = dict[index];
            dict.RemoveAt(index);
            dict.Insert(0, item);
        }

        /// <summary>
        /// 要排序字段个数
        /// </summary>
        public int Count
        {
            get
            {
                return dict == null ? 0 : dict.Count;
            }
        }

        /// <summary>
        /// 生成排序的SQL
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            if (dict == null || dict.Count == 0)
            {
                return string.Empty;
            }
            return " ORDER BY " + PTA.Convert.ToStrictString<KeyValuePair<string, OrderType>>(dict, 0, 0, item => { return string.Format("{0} {1}", item.Key, item.Value); });
        }
    }

    /// <summary>
    /// 字段排序类型
    /// </summary>
    public enum OrderType
    {
        /// <summary>
        /// 升序排序
        /// </summary>
        ASC,

        /// <summary>
        /// 降序排序
        /// </summary>
        DESC
    }

    #endregion

    #region SqlDataAccess

    /// <summary>
    /// 访问SQLServer的数据库的命令
    /// </summary>
    public class SqlDataCommand : DataCommand<SqlParameter>
    {
        private const string PARAMETERPREFIX = "@";
        protected override string ParameterPrefix
        {
            get
            {
                return PARAMETERPREFIX;
            }
        }

        public SqlDataCommand()
        {
        }

        public SqlDataCommand(string commandText)
            : base(commandText)
        { }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="commandText">数据库命令文本</param>
        /// <param name="commandType">数据库命令类型</param>
        /// <param name="parameters">数据库命令参数</param>
        public SqlDataCommand(string commandText, CommandType commandType, SqlParameter[] parameters) :
            base(commandText, commandType, parameters)
        {
        }

        public SqlParameter AddIn(string name, SqlDbType type)
        {
            var p = new SqlParameter(WrapParameterName(name), type);
            this.Add(p);
            return p;
        }

        public override SqlParameter AddIn(string name, object value)
        {
            name = WrapParameterName(name);
            if (value is bool)
            {
                return this.AddIn(name, SqlDbType.Int, (object)((bool)value ? 1 : 0));
            }
            if (value is int[] || value is List<int>)
            {
                return this.AddIn(name, SqlDbType.NVarChar, 4000, string.Join(",", (IEnumerable<int>)value));
            }
            if (value is long[] || value is List<long>)
            {
                return this.AddIn(name, SqlDbType.NVarChar, 4000, string.Join(",", (IEnumerable<long>)value));
            }
            if (value is string[] || value is List<string>)
            {
                return this.AddIn(name, SqlDbType.NVarChar, 4000, string.Join(",", (IEnumerable<string>)value));
            }
            return base.AddIn(name, value);
        }

        public SqlParameter AddIn(string name, SqlDbType type, int size)
        {
            return this.Add(new SqlParameter(WrapParameterName(name), type, size));
        }

        public SqlParameter AddIn(string name, SqlDbType type, int size, object value)
        {
            return this.Add(new SqlParameter(WrapParameterName(name), type, size) { Value = value });
        }

        public SqlParameter AddIn(string name, SqlDbType type, object value)
        {
            return this.Add(new SqlParameter(WrapParameterName(name), type) { Value = value });
        }

        public SqlParameter Add(string name, object value, SqlDbType type, ParameterDirection direction, int size)
        {
            return this.Add(new SqlParameter(WrapParameterName(name), type, size) { Direction = direction, Value = value });
        }

        public SqlParameter AddOut(string name, SqlDbType type)
        {
            var p = new SqlParameter(WrapParameterName(name), type) { Direction = ParameterDirection.Output };
            this.parameters.Add(p);
            return p;
        }

        public SqlParameter AddOut(string name, SqlDbType type, int size)
        {
            var p = new SqlParameter(WrapParameterName(name), type, size) { Direction = ParameterDirection.Output };
            this.parameters.Add(p);
            return p;
        }

        public SqlParameter AddReturn(string name, SqlDbType type)
        {
            var p = new SqlParameter(WrapParameterName(name), type) { Direction = ParameterDirection.ReturnValue };
            this.parameters.Add(p);
            return p;
        }

        public SqlParameter AddReturn(string name, SqlDbType type, int size)
        {
            var p = new SqlParameter(WrapParameterName(name), type, size) { Direction = ParameterDirection.ReturnValue };
            this.parameters.Add(p);
            return p;
        }

    }

    /// <summary>
    /// SQL分页检索命令
    /// </summary>
    public class SqlPageSearch : SqlDataCommand, IPageSearch<SqlParameter>
    {
        public override string CommandText
        {
            get
            {
                return string.Empty;
            }
            set
            {
                throw new Exception("分页命令不支持设置数据库命令,请需要其它属性设置");
            }
        }

        public override CommandType CommandType
        {
            get
            {
                return CommandType.Text;
            }
            set
            {
                throw new Exception("分页命令不支持设置数据库命令类型");
            }
        }

        List<string> wheres = new List<string>();

        #region 查询字段
        private string fieldsName = "*";
        /// <summary>
        /// 查询字段(如果不设置,默认返回*)
        /// </summary>
        public string FieldsName
        {
            get
            {
                return this.fieldsName;
            }
            set
            {
                this.fieldsName = (value ?? "*").Trim();
            }
        }
        #endregion

        #region 表名称
        private string tableName = string.Empty;
        /// <summary>
        /// 表名称
        /// </summary>
        public string TableName
        {
            get
            {
                return this.tableName;
            }
            set
            {
                this.tableName = (value ?? string.Empty).Trim();
            }
        }
        #endregion

        #region 主键字段
        private string primaryKey = string.Empty;
        /// <summary>
        /// 主键字段
        /// </summary>
        public string PrimaryKey
        {
            get
            {
                return this.primaryKey;
            }
            set
            {
                this.primaryKey = (value ?? string.Empty).Trim();
            }
        }
        #endregion

        #region 排序字段

        private OrderFieldCollection orderField = new OrderFieldCollection();
        /// <summary>
        /// 排序字段
        /// </summary>
        public OrderFieldCollection OrderField
        {
            get
            {
                return this.orderField;
            }
        }
        #endregion

        public void And(string sql, params string[] args)
        {
            wheres.Add(string.Format(sql, args));
        }

        public string Where
        {
            get
            {
                return PTA.Convert.ToStrictString(wheres, x => "(" + x + ")", " AND ");
            }
        }
        #region 当前页码
        private int pageIndex = 0;
        /// <summary>
        /// 当前页码(从0开始)
        /// </summary>
        public int PageIndex
        {
            get
            {
                return this.pageIndex;
            }
            set
            {
                this.pageIndex = value > 0 ? value : 0;
            }
        }
        #endregion

        #region 每页数量
        private int pageSize = 15;
        /// <summary>
        /// 每页数量(默认15),等于0时,查询全部
        /// </summary>
        public int PageSize
        {
            get
            {
                return pageSize;
            }
            set
            {
                if (value < 0)
                {
                    pageSize = Math.Abs(value);
                }
                else
                {
                    pageSize = value;
                }
            }
        }
        #endregion

        #region 记录总数
        private int totalCount;
        /// <summary>
        /// 记录总数
        /// </summary>
        public int TotalCount
        {
            get
            {
                return this.totalCount;
            }
            set
            {
                this.totalCount = value > 0 ? value : 0;
            }
        }
        #endregion

        #region 页数
        /// <summary>
        /// 总页数
        /// </summary>
        public int PageCount
        {
            get
            {
                if (PageSize == 0)
                {
                    return 1;
                }
                return (totalCount + pageSize - 1) / pageSize;
            }
        }
        #endregion

    }

    /// <summary>
    /// SQLServer数据库访问类
    /// </summary>
    public class SqlDataAccess : DataAccess<SqlConnection, SqlDataAdapter, SqlTransaction, SqlParameter, SqlDataCommand, SqlPageSearch>
    {
        private const string PARAMETERPREFIX = "@";
        public override string ParameterPrefix
        {
            get
            {
                return PARAMETERPREFIX;
            }
        }

        /// <summary>
        /// 默认的构造函数
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        public SqlDataAccess(string connectionString)
            : base(connectionString)
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="enablelog">是否记录数据库日志</param>
        public SqlDataAccess(string connectionString, bool enablelog)
            : base(connectionString)
        {
            this.WriteDebug = enablelog;
        }

        /// <summary>
        /// 默认的构造函数
        /// </summary>
        /// <param name="connectionBuilder">数据库连接字符串生成器</param>
        public SqlDataAccess(SqlConnectionStringBuilder connectionBuilder) :
            this(connectionBuilder.ConnectionString)
        {
        }
        /// <summary>
        /// 默认的构造函数
        /// </summary>
        /// <param name="connectionBuilder">数据库连接字符串生成器</param>
        public SqlDataAccess(SqlConnectionStringBuilder connectionBuilder, bool enablelog) :
            this(connectionBuilder.ConnectionString)
        {
            this.WriteDebug = enablelog;
        }


        /// <summary>
        /// 获取存储过程的参数
        /// </summary>
        /// <param name="procName">存储过程名称</param>
        /// <returns>存储过程的参数</returns>
        protected override SqlParameter[] GetProcParameters(string procName)
        {
            SqlParameter[] pvs = GrabParameters(procName);
            if (pvs == null)
            {
                using (SqlCommand cmd = new SqlCommand(procName, CreateConnection()))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection.Open();
                    SqlCommandBuilder.DeriveParameters(cmd);
                    cmd.Connection.Dispose();
                    #region 把Return参数放到最后面
                    var p = cmd.Parameters[0];
                    cmd.Parameters.RemoveAt(0);
                    cmd.Parameters.Add(p);
                    #endregion
                    pvs = new SqlParameter[cmd.Parameters.Count];
                    cmd.Parameters.CopyTo(pvs, 0);
                    SaveParameters(procName, pvs);
                    pvs = GrabParameters(procName);
                }
            }
            return pvs;
        }

        #region 参数管理

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="type">参数类型</param>
        /// <returns>数据库命令参数</returns>
        public SqlParameter MakeIn(string name, SqlDbType type)
        {
            return new SqlParameter(name, type);
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="type">参数类型</param>
        /// <param name="size">参数长度</param>
        /// <returns>数据库命令参数</returns>
        public SqlParameter MakeIn(string name, SqlDbType type, int size)
        {
            return new SqlParameter(name, type, size);
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="value">参数值</param>
        /// <param name="type">参数类型</param>
        /// <param name="size">参数长度</param>
        /// <returns>数据库命令参数</returns>
        public SqlParameter MakeIn(string name, SqlDbType type, int size, object value)
        {
            SqlParameter p = new SqlParameter(name, type);
            p.Value = value;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="type">参数类型</param>
        /// <returns>数据库命令参数</returns>
        public SqlParameter MakeOut(string name, SqlDbType type)
        {
            SqlParameter p = new SqlParameter(name, type);
            p.Direction = ParameterDirection.Output;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="type">参数类型</param>
        /// <param name="size">参数长度</param>
        /// <returns>数据库命令参数</returns>
        public SqlParameter MakeOut(string name, SqlDbType type, int size)
        {
            SqlParameter p = new SqlParameter(name, type, size);
            p.Direction = ParameterDirection.Output;
            return p;
        }

        /// <summary>
        /// 创建数据库命令参数
        /// </summary>
        /// <param name="name">参数名称</param>
        /// <param name="value">参数值</param>
        /// <param name="direction">参数方向</param>
        /// <param name="type">参数类型</param>
        /// <param name="size">参数长度</param>
        /// <returns>数据库命令参数</returns>
        public SqlParameter MakeParam(string name, object value, SqlDbType type, ParameterDirection direction, int size)
        {
            SqlParameter p = new SqlParameter(name, type);
            if (value != null)
            {
                p.Value = value;
            }
            if (size > 0)
            {
                p.Size = size;
            }
            p.Direction = direction;
            return p;
        }

        #endregion

        /// <summary>
        /// 将数据表内的数据批量写入到数据库
        /// </summary>
        /// <param name="dt">数据表</param>
        public void BulkCopy(DataTable dt)
        {
            if (dt == null)
            {
                throw new ArgumentNullException("dt");
            }
            if (string.IsNullOrEmpty(dt.TableName))
            {
                throw new ArgumentException("没有为参数dt指定表名");
            }
            if (dt.Rows.Count == 0)
            {
                return;
            }
            using (SqlBulkCopy bulk = new SqlBulkCopy(this.ConnectionString))
            {
                bulk.BatchSize = 100000;
                bulk.BulkCopyTimeout = 60;
                bulk.DestinationTableName = dt.TableName;
                bulk.WriteToServer(dt);
            }
        }

        /// <summary>
        /// 执行SQL脚本文件
        /// </summary>
        /// <param name="connection">数据库连接对象</param>
        /// <param name="path">脚本文件路径</param>
        public void ExecuteFile(string path)
        {
            if (!System.IO.File.Exists(path))
            {
                throw new Exception("文件未找到,文件路径:" + path);
            }
            using (SqlConnection connection = this.CreateConnection())
            using (System.IO.StreamReader reader = new System.IO.StreamReader(path))
            {
                IDbCommand cmd = connection.CreateCommand();
                cmd.Connection = connection;
                cmd.CommandType = CommandType.Text;
                cmd.CommandTimeout = 60;
                try
                {
                    if (connection.State != ConnectionState.Open)
                    {
                        connection.Open();
                    }
                    while (!reader.EndOfStream)
                    {
                        string sql = GetNextSql(reader);
                        if (!string.IsNullOrEmpty(sql))
                        {
                            cmd.CommandText = sql;
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new DataBaseException(WriteDbException(ex, cmd));
                }
                finally
                {
                    reader.Close();
                    connection.Close();
                }
            }
        }

        /// <summary>
        /// 从一个读取流中获取一条SQL语句
        /// </summary>
        /// <param name="reader">流</param>
        /// <param name="provider">数据库类型</param>
        /// <returns>读取到的SQL语句</returns>
        internal static string GetNextSql(StreamReader reader)
        {
            try
            {
                StringBuilder builder = new StringBuilder();
                string sql = reader.ReadLine().Trim();
                while (!reader.EndOfStream && (!sql.Equals("GO", StringComparison.OrdinalIgnoreCase)))
                {
                    if ((sql.Length > 0) && (!sql.StartsWith("--")) && (!(sql.StartsWith("/*") && sql.EndsWith("*/"))))
                    {
                        builder.Append(sql + Environment.NewLine);
                    }
                    sql = reader.ReadLine().Trim();
                }
                if ((!sql.Equals("GO", StringComparison.OrdinalIgnoreCase)))
                {
                    if ((sql.Length > 0) && (!sql.StartsWith("--")) && (!(sql.StartsWith("/*") && sql.EndsWith("*/"))))
                    {
                        builder.Append(sql + Environment.NewLine);
                    }
                }
                if (builder.Length == 0)
                {
                    return null;
                }
                return builder.ToString();
            }
            catch
            {
                return null;
            }
        }
    }
    #endregion
}